繁体   English   中英

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

[英]How do I count the number of occurrences of a character in a string?

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

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

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

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

改成:

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

您会超出范围,因为您没有遍历用户输入。

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,将其每个字母与原始char比较。 从theString中删除**,我刚刚添加了它以引起您对更改的注意。 我猜theString是在代码的其他地方定义的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM