【发布时间】:2016-10-11 00:56:37
【问题描述】:
我正在为我的班级编写一些代码,我遇到了这个错误,字符串索引超出范围。我检查了它是否可能是 string = null 但事实并非如此。我猜这与我在方法中的 if 语句有关,但我找不到如何在任何地方修复它。感谢您的帮助,非常感谢!
import java.util.*;
public class Occurences {
public static void main(String[] args) {
int check = 0;
char characterInput = ' ';
do {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string: ");
String input = scan.next();
System.out.println("Enter a character to find it's occurence in the string: ");
characterInput = scan.next().charAt(0);
int i = count(input, characterInput);
System.out.println(characterInput + ", is in " + input + ", " + i + " times.");
System.out.println("To continue enter any number, to exit enter -1: ");
check = scan.nextInt();
} while (check != -1);
}
public static int count(String input, char characterInput) {
int cnt = 0;
int j = input.length();
while (j > 0) {
if (input.charAt(j) == characterInput) {
cnt += 1;
}
j--;
}
return cnt;
}
}
【问题讨论】:
-
最后一个字符在索引
length()-1上,因为第一个索引是0。 -
当您尝试访问不存在的数组索引时,会发生 Java 索引超出范围错误。重要的是要注意 Java 数组以索引 0 开头。看看你是否能根据这个信息弄清楚。我不想泄露答案......它不会帮助你学习。
-
int j = input.length()-1;
-
感谢所有 cmets,我最终将 j 切换为 0 并递增,但我知道错误发生在哪里。
-
@GabrielTomasetto,请参阅下面的答案,我解释了您所做的工作的原因。如果我的回答有助于为您解释,请考虑支持并接受它作为答案。 =] 谢谢!