《Java语言程序设计(基础篇)》(第10版 梁勇 著)
第二十一章 练习题答案
21.1
import java.util.*;
public class Exercise21_01 {
public static void main(String[] args) {
LinkedHashSet
LinkedHashSet
LinkedHashSet
set1.addAll(set2);
set1Clone1.removeAll(set2); set1Clone2.retainAll(set2);
System.out.println(\ + set1);
System.out.println(\ + set1Clone1); System.out.println(\ + set1Clone2); } }
21.1附加
import java.util.*;
public class Exercise21_01Extra {
public static void main(String[] args) { System.out.print(\); Scanner input = new Scanner(System.in); String s = input.nextLine();
Character[] list1 = {'A', 'E', 'I', 'O', 'U'};
Set
int numbeOfVowels = 0; int numbeOfConsonants = 0;
for (int i = 0; i < s.length(); i++) {
char ch = Character.toUpperCase(s.charAt(i)); if (Character.isLetter(ch)) { if (vowels.contains(ch)) {
if (!vowelsInString.contains(ch)) { vowelsInString.add(ch); numbeOfVowels++; } }
else if (!consonantsInString.contains(ch)) { consonantsInString.add(ch); numbeOfConsonants++; } } }
System.out.println(\ + numbeOfVowels); System.out.println(\ + numbeOfConsonants); } }
21.2
import java.util.*; import java.io.*;
public class Exercise21_02 {
public static void main(String[] args) { if (args.length != 1) { System.out.println(
\); System.exit(1); }
String filename = args[0];
// Create a tree set to hold the words
TreeSet
try {
Scanner in = new Scanner(new File(filename));
String line;
while ((line = in.nextLine()) != null) {
String[] tokens = line.split(\);
for (int i = 0; i < tokens.length; i++) treeSet.add(tokens[i]); } }
catch (Exception ex) { System.err.println(ex); }
// Get an iterator for the set
Iterator iterator = treeSet.iterator();
// Display mappings
System.out.println(\); while (iterator.hasNext()) {
System.out.println(iterator.next()); } } }
21.3
import java.util.*; import java.io.*;
public class Exercise21_03 {
public static void main(String[] args) { // Check usage
if (args.length != 1) {
System.out.println(\); System.exit(1); }
// Array of all Java keywords + true + null
String[] keywordString = {\, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \,
\, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \, \};
Set
new HashSet
Scanner input = new Scanner(new File(args[0]));
String text = \;
while (input.hasNext()) {
String line = input.nextLine(); line = stripLineComments(line); line = stripLineStringLiterals(line); text += line + \; }
text = stripParagraghComments(text);
String[] tokens = text.split(\); for (String token: tokens) { if (keywordSet.contains(token)) count++; }
System.out.println(\ + count); }
catch (Exception ex) { ex.printStackTrace(); } }
/* Strip line comments */
private static String stripLineComments(String line) { int index = line.indexOf(\);
if (index < 0) return line; else