【问题标题】:Why does this lead to an ArrayIndexOutOfBoundsException?为什么这会导致 ArrayIndexOutOfBoundsException?
【发布时间】:2014-01-01 09:55:12
【问题描述】:

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

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

【问题讨论】:

    标签: java arrays runtime-error indexoutofboundsexception


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          '0'和0有很大的不同。'0'是“零”字符的代码。

          【讨论】:

          • 不要将零字符 '0' 与空字符 '\0' 混淆:)
          • @stuXnet 好吧,您也可以错误地解释“零字符”的措辞。 :)
          【解决方案5】:

          这就是问题所在:

           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']++;
              }
          }
          

          【讨论】:

          • 非常感谢!这现在更有意义了。
          • @Steve:- 你是不是想赶上超音速的 Jon Skeet! ;)
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-11-27
          • 1970-01-01
          • 2013-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多