为什么会导致ArrayIndexOutOfBoundsException?

时间:2013-12-13 15:12:32

标签: java arrays runtime-error indexoutofboundsexception

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

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;
}

在此时出现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;
    }

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

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

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 the count number method
int[] numbers = countNumbers(phone);

5 个答案:

答案 0 :(得分:8)

这是问题所在:

 counts[n.charAt(i)]++;

n.charAt(i)是一个字符,将转换为整数。所以'0'实际上是48,例如......但你的数组只有10个元素。

请注意,工作版本不减去0 - 它减去'0',或转换为int时为48。

基本上是这样的:

Character          UTF-16 code unit        UTF-16 code unit - '0'
'0'                48                      0
'1'                49                      1
'2'                50                      2
'3'                51                      3
'4'                52                      4
'5'                53                      5
'6'                54                      6
'7'                55                      7
'8'                56                      8
'9'                67                      9

但是,对于非ASCII数字,代码仍然被破坏。由于它只能处理ASCII数字,因此最好明确指出:

for (int i = 0; i < n.length(); i++){
    char c = n.charAt(i);
    if (c >= '0' && c <= '9') {
        counts[c - '0']++;
    }
}

答案 1 :(得分:0)

'0'与0完全不同.'0'是“零”字符的代码。

答案 2 :(得分:0)

问题出在counts[n.charAt(i)]行。此处n.charat(i)可能会返回大于9的值;

答案 3 :(得分:0)

这里的困惑是你在想'0' == 0。这不是真的。当被视为数字时,'0'具有字符0的ASCII值,即48。

答案 4 :(得分:0)

因为n.charAt(i)返回一个字符,然后将其装箱成一个数字。在这种情况下,字符0实际上是ASCII value 48

通过减去字符'0',您将减去值48并将索引置于0-9范围内,因为您已检查该字符是否为有效数字。

相关问题