java语言程序设计(进阶版)21.6 21.10 HashMap

it2025-09-25  3

package com.wenchi; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; import java.util.TreeMap; public class Demo01 { public static void main(String[] args) { HashMap<Integer, Integer> hashMap = new HashMap<>(); Scanner input = new Scanner(System.in); int t; while ((t = input.nextInt()) != 0) { if (hashMap.containsKey(t)) hashMap.put(t, hashMap.get(t).intValue() + 1); else hashMap.put(t, 1); } Iterator itr = hashMap.keySet().iterator(); int max = 0; while (itr.hasNext()) { if ((t = hashMap.get(itr.next()))>max) { max = t; } } int finalMax = max; hashMap.keySet().forEach(i->{ if(hashMap.get(i) == finalMax) System.out.println(i + " : " + hashMap.get(i)); }); } } package com.wenchi; import java.io.*; import java.util.*; public class text { public static void main(String[] args) throws Exception { Scanner input = new Scanner(System.in); System.out.println("Enter a Java source file name:"); String filename = input.nextLine(); File file = new File(filename); if (file.exists()) { System.out.println("The number of keywords in " + filename + " is " + wordTime(file)); } else { System.out.println("File " + filename + " does not exit"); } } public static int wordTime(File file) throws Exception { String[] keywordString = {"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "strictfp", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while"}; Set<String> workTimeSet = new HashSet<>(Arrays.asList(keywordString)); int count = 0; BufferedReader in = new BufferedReader(new FileReader(file));/*ffff*/ String str = null; boolean flag1 = false,flag2 = false; while ((str = in.readLine()) != null) { int t = 0; if (str.contains("//")) { str.replace("{", " ").replace("}", " ").replace("(", " ").replace(")", " ").replace("[", " ").replace(";", " "); str = str.substring(0, str.indexOf("//")); } else if (str.contains("/*")) { str = str.substring(0, str.indexOf("/*")); flag1 = true; } else if (str.contains("*/")) { str = str.substring(0, str.indexOf("*/")); flag1 = false; } String[] strs = str.split(" "); System.out.println(str); if(flag2 == false) for(String s: strs){ System.out.println("."+s); if(workTimeSet.contains(s)) count++; } flag2 = flag1; } in.close(); return count; } }
最新回复(0)