2014-09-30 200 views
0

我写了一段代码,它一直给我一个ArrayIndexOutOfBoundsException错误,我不知道为什么。我想我已经正确设置了阵列的大小,但显然这是不正确的。即使我将数组的大小设置为100,我仍然得到错误。在代码下方可以找到数据输入。不知道是什么原因导致我的ArrayIndexOutOfBoundsException错误

import java.util.Scanner; 

public class GameOfLife { 

public static void main(String []args) { 

    Scanner scanner = new Scanner(System.in); 

    int length = scanner.nextInt(); 
    int width = scanner.nextInt(); 
    int generations = scanner.nextInt(); 
    Boolean[][] cellsInput = new Boolean[length - 1][width - 1]; 

    System.out.println(); 
    int count = 0; 
    int y = 0; 
    while (scanner.hasNext()) { 
     count++; 
     if (count <= length) { 
      if (scanner.next().equals(".")){ 
       cellsInput[y++][count] = false; 
      } else if (scanner.next().equals("*")) { 
       cellsInput[y++][count] = true; 
      } 
     } 
     else { 
      count = 0; 
      y++; 
      if (scanner.next().equals(".")){ 
       cellsInput[y++][count] = false; 
      } else if (scanner.next().equals("*")) { 
       cellsInput[y++][count] = true; 
      } 
     } 
    } 

} 

}

(例如)输入:

15 15 3 
. . . . . . . . . . . . . * . 
. . . . . . . . . . . . * . . 
. . . . . . . . . . . . * * * 
. . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . 
* * * * * * * * . . . . . . . 
. . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . 
. . . . . . . . . . . . . . . 
+0

不要“认为”您已正确设置尺寸:请检查。使用一些战术性的'System.out.println()'语句*验证你的索引是否在有效范围内。 – 2014-09-30 00:34:31

+0

这个Boolean [] [] cellsInput = new Boolean [length - 1] [width - 1];'也是错误的。 – 2014-09-30 00:38:05

+0

查看异常堆栈跟踪以确定发生异常的位置。在该语句之前添加println语句以打印索引值和数组大小。确定哪些值出错。然后通过代码反向工作,找出为什么这个值是错误的。这是基本的调试过程。 – 2014-09-30 00:43:52

回答

2

的问题是在这里:

if (count <= length) { 

最终,这会尝试引用

cellsInput[y++][length] 

其中长度是第二个数组的长度。但是,第二个数组中的最后一个索引实际上是length - 1

这里出现的问题是因为Java中的所有数组都以0开头。所以你总是想做

if (count < length) { 

只要长度是长度就是数组的长度。

长度始终是数组中的对象数,它从1开始计数。

实施例:

Array arr1 = [a, b, c, d] 
Length of arr1 = 4, it has 4 elements 

Element | Index 
-------------------- 
    a  | 0 
    b  | 1 
    c  | 2 
    d  | 3 

正如你可以看到索引图4是出界。因此,当您尝试引用arr1[arr1.length]时,您将得到一个IndexOutOfBoundsException

4

例如下面一行是错误的:

if (count <= length) { 

由于您使用数作为指标,当计数等于长度超过最大索引length - 1 - 因此ArrayIndexOutOfBoundsException。它应该是:

if (count < length) { 
相关问题