打印唯一字符及其出现次数

4

我是一名新手,对于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  

我该如何修复这个问题?

5个回答

3

iint类型,因此您正在打印每个char的整数值。您需要将其转换为char才能看到字符。

更改

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

to

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

3

你正在将索引打印为int类型。在打印之前尝试将其强制转换为char类型:

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

2

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

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]);
            }
        }
    }

}  

这应该可以工作。

更多阅读:

如何将 ASCII 码(0-255)转换为相应字符的字符串?


2

您正在打印每个字符的ASCIIint表示。您需要通过转换来将它们转换为char,即进行强制类型转换 -

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

1

您的testCharArray是一个int数组。您在其中存储了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.
    }
} 

这个转换将整数转换为字符。每个字符都有一个整数值。例如 -
'a' 的 int 值为 97。 'b' 的 int 值为 98。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接