Microsoft Word - sy09_实验09_字符串和文本IO.docx

Similar documents
CC213

JavaIO.PDF

3.1 num = 3 ch = 'C' 2

untitled

<4D F736F F F696E74202D C DB5DA3039D5C25FD7D6B7FBB4AEBACDCEC4B1BE494F2E BBCE6C8DDC4A3CABD5D>

Java Access 5-1 Server Client Client Server Server Client 5-2 DataInputStream Class java.io.datainptstream (extends) FilterInputStream InputStream Obj

Chapter 9: Objects and Classes

使 用 Java 语 言 模 拟 保 险 箱 容 量 门 板 厚 度 箱 体 厚 度 属 性 锁 具 类 型 开 保 险 箱 关 保 险 箱 动 作 存 取 款

Microsoft Word - 01.DOC

Microsoft PowerPoint - string_kruse [兼容模式]

概述

Microsoft Word - ch04三校.doc

untitled

C 1

Chapter 9: Objects and Classes

Java java.lang.math Java Java.util.Random : ArithmeticException int zero = 0; try { int i= 72 / zero ; }catch (ArithmeticException e ) { // } 0,

Java

1 Project New Project 1 2 Windows 1 3 N C test Windows uv2 KEIL uvision2 1 2 New Project Ateml AT89C AT89C51 3 KEIL Demo C C File

Microsoft PowerPoint - L17_Inheritance_v4.pptx

《大话设计模式》第一章

Python a p p l e b e a r c Fruit Animal a p p l e b e a r c 2-2

科学计算的语言-FORTRAN95

51 C 51 isp 10 C PCB C C C C KEIL

FY.DOC

C/C++语言 - 分支结构

C/C++ 语言 - 循环

Fun Time (1) What happens in memory? 1 i n t i ; 2 s h o r t j ; 3 double k ; 4 char c = a ; 5 i = 3; j = 2; 6 k = i j ; H.-T. Lin (NTU CSIE) Referenc

全国计算机技术与软件专业技术资格(水平)考试

chp6.ppt

新版 明解C++入門編

1 Framework.NET Framework Microsoft Windows.NET Framework.NET Framework NOTE.NET NET Framework.NET Framework 2.0 ( 3 ).NET Framework 2.0.NET F

C/C++语言 - C/C++数据

Guava学习之Resources

新・明解C言語入門編『索引』

1.JasperReport ireport JasperReport ireport JDK JDK JDK JDK ant ant...6

Java 程式設計初階 第 5 章:基本輸出入 & 流程控制

AN INTRODUCTION TO PHYSICAL COMPUTING USING ARDUINO, GRASSHOPPER, AND FIREFLY (CHINESE EDITION ) INTERACTIVE PROTOTYPING

Microsoft Word - CPE考生使用手冊 docx

Learning Java

EJB-Programming-4-cn.doc

untitled

Spyder Anaconda Spyder Python Spyder Python Spyder Spyder Spyder 開始 \ 所有程式 \ Anaconda3 (64-bit) \ Spyder Spyder IPython Python IPython Sp

C H A P T E R 7 Windows Vista Windows Vista Windows Vista FAT16 FAT32 NTFS NTFS New Technology File System NTFS

RxJava

雲端 Cloud Computing 技術指南 運算 應用 平台與架構 10/04/15 11:55:46 INFO 10/04/15 11:55:53 INFO 10/04/15 11:55:56 INFO 10/04/15 11:56:05 INFO 10/04/15 11:56:07 INFO


CC213

javaexample-02.pdf

Microsoft PowerPoint - course2.ppt

mvc

JBuilder Weblogic

内 容 简 介 本 书 是 一 本 关 于 语 言 程 序 设 计 的 教 材, 涵 盖 了 语 言 的 基 本 语 法 和 编 程 技 术, 其 中 包 含 了 作 者 对 语 言 多 年 开 发 经 验 的 总 结, 目 的 是 让 初 学 的 读 者 感 受 到 语 言 的 魅 力, 并 掌

PowerPoint Presentation

Microsoft PowerPoint - 20-string-s.pptx

第3章.doc

(TestFailure) JUnit Framework AssertionFailedError JUnit Composite TestSuite Test TestSuite run() run() JUnit

2009年3月全国计算机等级考试二级Java语言程序设计笔试试题

OOP with Java 通知 Project 3 提交时间 3 月 29 日晚 9 点 Piazza Project 2 投票

PowerPoint 簡報

BOOL EnumWindows(WNDENUMPROC lparam); lpenumfunc, LPARAM (Native Interface) PowerBuilder PowerBuilder PBNI 2

附录J:Eclipse教程

第一章

, 7, Windows,,,, : ,,,, ;,, ( CIP) /,,. : ;, ( 21 ) ISBN : -. TP CIP ( 2005) 1

epub83-1

《C语言程序设计》教材习题参考答案

27 :OPC 45 [4] (Automation Interface Standard), (Costom Interface Standard), OPC 2,,, VB Delphi OPC, OPC C++, OPC OPC OPC, [1] 1 OPC 1.1 OPC OPC(OLE f

OOP with Java 通知 Project 4: 4 月 18 日晚 9 点 关于抄袭 没有分数

OOP with Java 通知 Project 2 提交时间 : 3 月 14 日晚 9 点 另一名助教 : 王桢 学习使用文本编辑器 学习使用 cmd: Power shell 阅读参考资料

untitled

ebook39-6

Microsoft Word - Learn Objective-C.doc

Microsoft Word - template.doc

华恒家庭网关方案

EJB-Programming-3.PDF

Microsoft Word - 苹果脚本跟我学.doc

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

使用MapReduce读取XML文件

untitled

nooog

(HMI) IO A

( CIP) /. :, ( ) ISBN TP CIP ( 2005) : : : : * : : 174 ( A ) : : ( 023) : ( 023)

第3章 Java语言基础

Microsoft PowerPoint - Lecture7II.ppt

an153f

基于CDIO一体化理念的课程教学大纲设计

OOP with Java 通知 : Project 2 提交时间 : 3 月 14 日晚 9 点 另一名助教 : 王桢

OOP with Java 通知 : Project 2 提交时间 : 3 月 15 日晚 9 点

OOP with Java 通知 Project 4: 5 月 2 日晚 9 点

SDK 概要 使用 Maven 的用户可以从 Maven 库中搜索 "odps-sdk" 获取不同版本的 Java SDK: 包名 odps-sdk-core odps-sdk-commons odps-sdk-udf odps-sdk-mapred odps-sdk-graph 描述 ODPS 基

Microsoft Word - linux命令及建议.doc

C语言的应用.PDF

96年特種考試第一次司法人員考試試題解答

untitled

Tel:

Important Notice SUNPLUS TECHNOLOGY CO. reserves the right to change this documentation without prior notice. Information provided by SUNPLUS TECHNOLO

Microsoft PowerPoint - ds-1.ppt [兼容模式]

untitled

Transcription:

面向对象程序设计 (Java) 课程实验 第 9 章字符串和文本 I/O 9.1 找出回文串检测一个字符串是否是回文串 : 从前向后和从后向前读都是同一个字符串的字符串 public class CheckPalindrome { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter a string: "); String s = input.nextline(); if (ispalindrome(s)) System.out.println(s + " is a palindrome"); else System.out.println(s + " is not a palindrome"); /** Check if a string is a palindrome */ public static boolean ispalindrome(string s) { // The index of the first character in the string int low = 0; // The index of the last character in the string int high = s.length() - 1; while (low < high) { if (s.charat(low)!= s.charat(high)) return false; // Not a palindrome low++; high--; return true; // The string is a palindrome 9.2 统计字符串中每个字母的出现次数统计在忽略字母大小写的情况下, 字符串中每个字母出现的次数 public class CountEachLetter {

// Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter a string: "); String s = input.nextline(); // Invoke the countletters method to count each letter int[] counts = countletters(s.tolowercase()); // Display results for (int i = 0; i < counts.length; i++) { if (counts[i]!= 0) System.out.println((char)('a' + i) + " appears " + counts[i] + ((counts[i] == 1)? " time" : " times")); /** Count each letter in the string */ public static int[] countletters(string s) { int[] counts = new int[26]; for (int i = 0; i < s.length(); i++) { if (Character.isLetter(s.charAt(i))) counts[s.charat(i) - 'a']++; return counts; 9.3 忽略既非字母又非数字的字符来判断回文串检测一个字符串在忽略掉非字母和非数字的字符后, 它是否是一个回文串 public class PalindromeIgnoreNonAlphanumeric { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter a string: "); String s = input.nextline(); // Display result System.out.println("Ignoring non-alphanumeric characters, \nis " + s + " a palindrome? " + ispalindrome(s)); /** Return true if a string is a palindrome */ public static boolean ispalindrome(string s) { // Create a new string by eliminating non-alphanumeric chars String s1 = filter(s);

// Create a new string that is the reversal of s1 String s2 = reverse(s1); // Compare if the reversal is the same as the original string return s2.equals(s1); /** Create a new string by eliminating non-alphanumeric chars */ public static String filter(string s) { // Create a string builder StringBuilder stringbuilder = new StringBuilder(); // Examine each char in the string to skip alphanumeric char for (int i = 0; i < s.length(); i++) { if (Character.isLetterOrDigit(s.charAt(i))) { stringbuilder.append(s.charat(i)); // Return a new filtered string return stringbuilder.tostring(); /** Create a new string by reversing a specified string */ public static String reverse(string s) { StringBuilder stringbuilder = new StringBuilder(s); stringbuilder.reverse(); // Invoke reverse in StringBuilder return stringbuilder.tostring(); 9.4 计算器编写一个程序, 完成整数的算术运算 该程序接收三个参数 : 一个操作符和两个整数 public class Calculator { // Check number of strings passed if (args.length!= 3) { System.out.println( "Usage: java Calculator operand1 operator operand2"); // The result of the operation int result = 0; // Determine the operator switch (args[1].charat(0)) { case '+': result = Integer.parseInt(args[0]) + break; case '-': result = Integer.parseInt(args[0]) -

break; case '*': result = Integer.parseInt(args[0]) * break; case '/': result = Integer.parseInt(args[0]) / // Display result System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result); 9.5 使用 PrintWriter 写数据 java.io.printwriter +PrintWriter(filename: String) +print(s: String): void +print(c: char): void +print(carray: char[]): void +print(i: int): void +print(l: long): void +print(f: float): void +print(d: double): void +print(b: boolean): void Also contains the overloaded println methods. Also contains the overloaded printf methods. 为特定的文件名字符串创建一个 PrintWriter 对象向文件写入一个字符串向文件写入一个字符向文件写入一个字符数组向文件写入一个 int 型值向文件写入一个 long 型值向文件写入一个 float 型值向文件写入一个 double 型值向文件写入一个 boolean 型值 Println 方法除了可以打印一个行分隔符之外, 其他都和 print 方法一样 行分隔符字符串是由系统定义的 在 Windows 系统是 \r\n, 在 UNIX 系统中是 \n Printf 方法在 3.17 节中介绍 public class WriteData { java.io.file file = new java.io.file("scores.txt"); if (file.exists()) { System.out.println("File already exists"); // Create a file java.io.printwriter output = new java.io.printwriter(file); // Write formatted output to the file output.print("john T Smith "); output.println(90); output.print("eric K Jones "); output.println(85); // Close the file output.close();

9.6 使用 Scanner 读数据 java.util.scanner +Scanner(source: File) +Scanner(source: String) +close() +hasnext(): boolean +next(): String +nextbyte(): byte +nextshort(): short +nextint(): int +nextlong(): long +nextfloat(): float +nextdouble(): double +usedelimiter(pattern: String): Scanner 创建一个所产生的值都是从特定文件扫描而来的扫描器. 创建一个所产生的值都是从特定字符串扫描而来的扫描器关闭这个扫描器如果这个扫描器还有可读的数据则返回 true 从这个扫描器返回下一个标志作为字符串从这个扫描器中返回下一个标志作为一个 byte 值从这个扫描器中返回下一个标志作为一个 short 值从这个扫描器中返回下一个标志作为一个 int 值从这个扫描器中返回下一个标志作为一个 long 值从这个扫描器中返回下一个标志作为一个 float 值从这个扫描器中返回下一个标志作为一个 double 值设置这个扫描器的分隔模式并返回这个扫描器 public class ReadData { // Create a File instance java.io.file file = new java.io.file("scores.txt"); // Create a Scanner for the file Scanner input = new Scanner(file); // Read data from a file while (input.hasnext()) { String firstname = input.next(); String mi = input.next(); String lastname = input.next(); int score = input.nextint(); System.out.println( firstname + " " + mi + " " + lastname + " " + score); // Close the file input.close(); 9.7 替换文本编写一个名为 ReplaceText 的类, 它用一个新字符串替换文本文件中所有出现某个字符串的地方 文件名和字符串都作为命令行参数传递, 如下所示 : java ReplaceText sourcefile targetfile oldstring newstring 例如 : 调用 java ReplaceText FormatString.java t.txt StringBuilder StringBuffer 就会用 StringBuffer 替换 FormatString.java 中所有出现的 StringBuilder, 然后将新文件保存在 t.txt 中

import java.io.*; import java.util.*; public class ReplaceText { // Check command line parameter usage if (args.length!= 4) { System.out.println( "Usage: java ReplaceText sourcefile targetfile oldstr newstr"); // Check if source file exists File sourcefile = new File(args[0]); if (!sourcefile.exists()) { System.out.println("Source file " + args[0] + " does not exist"); // Check if target file exists File targetfile = new File(args[1]); if (targetfile.exists()) { System.out.println("Target file " + args[1] + " already exists"); // Create input and output files Scanner input = new Scanner(sourceFile); PrintWriter output = new PrintWriter(targetFile); while (input.hasnext()) { String s1 = input.nextline(); String s2 = s1.replaceall(args[2], args[3]); output.println(s2); input.close(); output.close(); 9.8 (GUI) 文件对话框

import javax.swing.jfilechooser; public class ReadFileUsingJFileChooser { JFileChooser filechooser = new JFileChooser(); if (filechooser.showopendialog(null) == JFileChooser.APPROVE_OPTION) { // Get the selected file java.io.file file = filechooser.getselectedfile(); // Create a Scanner for the file Scanner input = new Scanner(file); // Read text from the file while (input.hasnext()) { System.out.println(input.nextLine()); // Close the file input.close(); else { System.out.println("No file selected");