輸入一段字串,統計其中字母、數字、空格等的個數
阿新 • • 發佈:2021-01-12
package test3; import java.util.HashMap; import java.util.Map.Entry; import java.util.Scanner; public class Count { public static void simpleCount(String str) { int i=0,count1=0,count2=0,count3=0,count4=0; while(i<str.length()) { if((str.charAt(i)<='Z' && str.charAt(i)>='A') || str.charAt(i)<='z' && str.charAt(i)>='a') { count1++; } else if(str.charAt(i)>='0' && str.charAt(i)<='9') { count2++; } else if(str.charAt(i)==' ') { count3++; } else { count4++; } i++; } System.out.println("字母個數:" + count1 + "\n數字個數:" + count2 + "\n空格個數:" + count3 + "\n其它字元個數:" + count4); } public static void detailCount(String str) { HashMap<Character,Integer> map = new HashMap<>(); int i=0; while(i<str.length()) { if(map.containsKey(str.charAt(i))) { map.put(str.charAt(i), map.get(str.charAt(i))+1); } else { map.put(str.charAt(i), 1); } i++; } System.out.println("\n詳細統計:"); for(Entry<Character, Integer> entry:map.entrySet()){ System.out.println(entry.getKey() + ":\t" + entry.getValue()); } } public static void main(String args[]) { Scanner sc=new Scanner(System.in); String str=new String(); str=sc.nextLine(); sc.close(); simpleCount(str); detailCount(str); } }