打印独特的字符及其出现

printing unique char and their occurrence

我是 java 新手,也是编程新手。我已经分配了一个任务来计算唯一字符的出现次数。我只需要使用 大批。我已经做了流动的代码 -

public class InsertChar{

    public static void main(String[] args){

        int[] charArray = new int[1000];
        char[] testCharArray = {'a', 'b', 'c', 'x', 'a', 'd', 'c', 'x', 'a', 'd', 'a'};

        for(int each : testCharArray){

            if(charArray[each]==0){
                charArray[each]=1;
            }else{
                ++charArray[each];
            }

        }

        for(int i=0; i<1000; i++){
            if(charArray[i]!=0){
                System.out.println( i +": "+ charArray[i]);
            }
        }
    }

}  

对于 testCharArray 输出应该是 -

a: 4
b: 1
c: 2
d: 2
x: 2  

但它给了我以下输出 -

97: 4
98: 1
99: 2
100: 2
120: 2  

我该如何解决这个问题?

iint,因此您要打印每个 char 的整数值。您必须将其转换为 char 才能看到字符。

改变

System.out.println( i +": "+ charArray[i]);

System.out.println( (char)i +": "+ charArray[i]);

您正在将索引打印为 int。在打印之前尝试将其转换为 char

for (int i=0; i<1000; i++){
    if (charArray[i]!=0){
        System.out.println( ((char) i) +": "+ charArray[i]);
    }
}

你的testCharArray是一个整型数组。您已经在其中存储了 char。所以你必须将字符转换为 int。 您必须在最后一个 for 循环中进行更改 -

for(int i=0; i<1000; i++){
    if(charArray[i]!=0){
        System.out.println( (char)i +": "+ charArray[i]); //cast int to char.
    }
} 

此转换将 int 转换为 char。每个字符都有一个 int 值。例如 -

'a' 有 97,因为它是 int
'b' 有 98,因为它是 int

您的程序正在打印 ascii 字符表示。您只需要将 acsii 数字转换为字符。

public class InsertChar{

    public static void main(String[] args){

        int[] charArray = new int[1000];
        char[] testCharArray = {'a', 'b', 'c', 'x', 'a', 'd', 'c', 'x', 'a', 'd', 'a'};

        for(int each : testCharArray){

            if(charArray[each]==0){
                charArray[each]=1;
            }else{
                ++charArray[each];
            }

        }

        for(int i=0; i<1000; i++){
            if(charArray[i]!=0){
                System.out.println( **(char)**i +": "+ charArray[i]);
            }
        }
    }

}  

这应该有效。

进一步阅读:

How to convert ASCII code (0-255) to a String of the associated character?

您正在打印每个 charASCII int 表示。您必须通过转换将它们转换为 char -

System.out.println( (char)i +": "+ charArray[i]);