如何计算字符串中字符的出现次数?

时间:2014-10-14 20:41:40

标签: java counter

System.out.print("Enter a character: ");
        String userInput= keyb.next();
        char i = userInput.charAt(0); //getting the character by itself
        int counter=0;
        for(int index= 0; index < theString.length(); index++)
        {
            char ch = userInput.charAt(index);
            if (ch==i) //comparing the chosen character to each character in the string
                counter++; //keeping track of how many times you find a match

我是编程的新手,我必须编写一个程序,用于计算用户在字符串中选择的字符出现次数,该字符串也是输入。这只是程序中存在问题的部分,运行时得到的错误是:线程中的异常&#34; main&#34; java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:1。不确定我做错了什么!

4 个答案:

答案 0 :(得分:1)

    for(int index= 0; index< theString.length(); index++)

theString来自哪里?我怀疑你的意思是userInput

答案 1 :(得分:1)

更改为:

System.out.print("Enter a character: ");
        String userInput= keyb.next();
        char i = userInput.charAt(0);//getting the character by itself
        int counter=0;
        for(int index= 0; index< userInput.length(); index++)
        {
            char ch = userInput.charAt(index);
            if (ch==i)//comparing the chosen character to each character in the string
                counter++;//keeping track of how many times you find a match

你得到了超出范围,因为你没有迭代用户输入。

答案 2 :(得分:1)

System.out.print("Enter a character: ");
        String userInput= keyb.next();
        char i = userInput.charAt(0);//getting the character by itself
        int counter=0;
        for(int index= 0; index< theString.length(); index++)
        {
            char ch = **theString**.charAt(index);
            if (ch==i)//comparing the chosen character to each character in the string
                counter++;//keeping track of how many times you find a match

我的假设是你要遍历theString,将每个字母与原始字符进行比较。从theString中删除**我刚刚添加它以引起你对变化的注意。我猜测theString是在代码的其他地方定义的。

答案 3 :(得分:-1)

检查堆栈跟踪中的行号,然后进行调试。