java中使用Map集合判斷字串中字元出現次數
阿新 • • 發佈:2018-11-25
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Test {
public static void main(String[] args) {
System.out.println("*********請輸入字串************");
Scanner scanner=new Scanner(System.in);
String string=scanner.next();
Map map=new HashMap<Character,Integer>();
char[]arrchar=string.toCharArray();
for (int i = 0; i < arrchar.length; i++) {
map.put(arrchar[i], 0);
}
for (int i = 0; i < arrchar.length; i++) {
if(map.containsKey(arrchar[i])){
int temp=(Integer)map.get(arrchar[i]);
temp++;
map.put(arrchar[i],temp);
}
}
System.out.println("*********字元出現次數************");
String string2= map.toString();
System.out.println(string2);
}
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Test {
public static void main(String[] args) {
System.out.println("*********請輸入字串************");
Scanner scanner=new Scanner(System.in);
String string=scanner.next();
Map map=new HashMap<Character,Integer>();
char[]arrchar=string.toCharArray();
for (int i = 0; i < arrchar.length; i++) {
map.put(arrchar[i], 0);
}
for (int i = 0; i < arrchar.length; i++) {
if(map.containsKey(arrchar[i])){
int temp=(Integer)map.get(arrchar[i]);
map.put(arrchar[i],temp);
}
}
System.out.println("*********字元出現次數************");
String string2= map.toString();
System.out.println(string2);
}
}