小编Bri*_*ian的帖子

为什么会导致ArrayIndexOutOfBoundsException?

有些东西对我来说没有意义.为什么这样:

public static int[] countNumbers(String n){
int[] counts = new int[10];

for (int i = 0; i < n.length(); i++){
    if (Character.isDigit(n.charAt(i)))
        counts[n.charAt(i)]++;
}
return counts;
}
Run Code Online (Sandbox Code Playgroud)

在此时出现ArrayOutOfBounds错误:

  public static int[] countNumbers(String n){
    int[] counts = new int[10];

    for (int i = 0; i < n.length(); i++){
        if (Character.isDigit(n.charAt(i)))
            counts[n.charAt(i) - '0']++;
    }
    return counts;
    }
Run Code Online (Sandbox Code Playgroud)

才不是?两个示例之间的唯一区别是在第二个示例中计数的索引被减去零.如果我没有错,那么第一个示例是否应该正确显示,因为正在检查相同的值?

以下是两种方法传递的值:

System.out.print("Enter a string: ");
String phone = input.nextLine();

//Array that invokes the count letter method
int[] letters = countLetters(phone.toLowerCase());

//Array that invokes …
Run Code Online (Sandbox Code Playgroud)

java arrays runtime-error indexoutofboundsexception

0
推荐指数
1
解决办法
130
查看次数