java - 如何计算字符串中某个字符出现的次数?

标签 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

我是编程新手,我必须编写一个程序来计算用户选择的字符在同时也是输入的字符串中出现的次数。这只是程序中有问题的部分,我在运行时得到的错误是: Exception in thread "main"java.lang.StringIndexOutOfBoundsException: String index out of range: 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 是在您的代码中的其他地方定义的。

关于java - 如何计算字符串中某个字符出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26369907/

相关文章:

java - 使用 MVP 模式在 GWT 中保存导航/历史状态

java - 如何区分importData中的复制/移动

java - 在 getter/setter 中创建一个计数器?

c - 如何使用 C 计算文本文件中特定字符串的出现次数

Javascript:循环到任何带有偶数/奇数描述的数字。为什么它只记录用户输入?

java - Android 应用程序 - 共享首选项未正确加载

java - 一个集合中不同类型对象的其他选项

java - 比较java中包含相同对象的两个ArrayLists

flutter - Dart - 在 x 秒后执行函数,除非被事件取消

C++ 第二个计数器