我的代码中有问题,我要求查找字符串中字符的出现次数,但我一直有异常错误,我不知道为什么?这是我的代码:
import java.io.IOException;
import java.util.*;
import java.lang.*;
public class LabOne1 {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String strUser = scan.next().toLowerCase();
System.out.print("Enter a character: ");
char charUser = (char) System.in.read();
Character.toLowerCase(charUser);
System.out.print(charUser + "occurs " + count(strUser, charUser) +
" times in the string " + strUser);
}
public static int count(String str, char a){
int counter = 0;
for(int i = 0; i <= str.length(); i++){
if (str.charAt(i) == a){
counter++;
}
}
return counter;
}
}
答案 0 :(得分:3)
您的字符串索引不正确。有效索引介于0和0之间,str.length()
独占。您的循环可以这样工作:
for(int i = 0; i < str.length(); i++) {
if (str.charAt(i) == a) counter++;
}
或者,您可以这样做:
int count = Math.toIntExact(str.chars().filter(ch -> ch == a).count());