实验八 规则集和映射
【实验目的和要求】
- 能够使用HashSet、LinkedHashSet或TreeSet来存储元素;
- 区分Collection与Map,能够理由合适的类来存储带键值的值。
【实验内容】
- 按升序显示不重复的单词,编写一个程序,从控制台读取英文段落,以新的一行****作为结束行,将所有不重复的单词按升序显示。
import java.util.Scanner; import java.util.Set; import java.util.TreeSet; class Main{ public static void main(String[] args) { Set<String> set = new TreeSet<>(); Scanner sc = new Scanner(System.in); String input, str = ""; while (!(input = sc.nextLine()).equals("****")) { str += input; } String[] strs = str.split("\\s|\\.|\\,"); for (String s : strs) { set.add(s); } for (String s : set) { System.out.println(s); } } }
- 读取个数不定的整数,查找其中出现频率最高的数字,当输入为0时,表示输入结束。如果输入的频率最高的数字不是一个,而是多个,则把多个数字都显示出来。
import java.util.Map; import java.util.Scanner; import java.util.TreeMap; class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); Map<Integer, Integer> map = new TreeMap<>(); int input, max = 0; do { input = sc.nextInt(); if (!map.containsKey(input)) { map.put(input, 0); } else { int count = map.get(input); count++; map.put(input, count); if (count > max) { max = count; } } } while (input != 0); for (Integer k : map.keySet()) { Integer v = map.get(k); if (v == max) { System.out.println(k); } } } }
- 统计java源代码中的关键字。如果关键字在注释或者字符串中,则不统计。将java源代码从控制台输入,以新的一行****作为结束行。
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; class Main { public static void main(String[] args) { Set<String> set = new TreeSet<>(); Scanner sc = new Scanner(System.in); String input, str = ""; while (!(input = sc.nextLine()).equals("****")) { str += input + "\n"; } String[] strs = str.split("\\s|\\.|\\,"); System.out.println("The number of keywords is " + countKeywords(strs)); } public static int countKeywords(String[] strs) { int count = 0; String[] keywordString = { "abstract", "finally", "public", "boolean", "float", "return", "break", "for", "short", "byte", "goto", "static", "case", "if", "super", "catch", "implements", "switch", "char", "import", "synchronized", "class", "instanceof", "this", "const", "int", "throw", "continue", "interface", "throws", "default", "long", "transient", "do", "native", "try", "double", "new", "void", "else", "package", "volatile", "extends", "private", "while", "final", "protected", "true", "null" }; Set<String> set = new HashSet<>(Arrays.asList(keywordString)); for (String s : strs) { if (set.contains(s)) { count++; } } return count; } }