面向对象程序设计 (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");