这是一个作业题。
我还遇到两次了…
利用map集合嘿哈哈搞定…
import java.util.HashMap;
import java.util.Scanner;public class CaclulateNum {public static void main(String[] args) {// 2:输入字符串统计字符串中每个字符出现的次数showNum();}static void showNum() {Scanner sc = new Scanner(System.in);try {System.out.println("请输入字符串:");String str = sc.nextLine();char[] charArray = str.toCharArray();HashMap<Character, Integer> hs = new HashMap<Character, Integer>();for (int i = 0; i < charArray.length; i++) {int count = 0;if (hs.containsKey(charArray[i])) { // 得到存在的字符个数count = hs.get(charArray[i]);// 存在就加1个count ++;// 覆盖,但是个数增加了hs.put(charArray[i], count);} else {// 这个字符不存在,长度是一个字符hs.put(charArray[i], 1);}}System.out.println(hs);} catch(Exception e) {e.printStackTrace();} finally {sc.close();}}}
关于scanner sc的说明
1,next() 带空格,table,enter next()就结束了 nextLine()遇到enter键结束.
2,用sc.next()时, sc.next() 和 sc.nextLine() 同用