gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:43:09 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com