2014-01-29 90 views
0

基本上,我得到了第19行的一个ArrayOutOfBounds异常。我试图在不分配任何值的情况下裁剪数组的内容(注释掉了wile循环),但仍然出现相同的错误,任何人有修复?数组越界异常,找不到问题

package com.company; 

import java.util.Random; 

public class Main { 
    static int[][] Placer = new int[2][2]; //create multi-dimenstional array to hold the numbers 

    public static void main(String[] args) { 
     Random random = new Random(); //intiallise new Random object 
     int intsAssigned = 0; //will keep track of the ammount of ints assigned. 



     //Assign all of the index's a random int, not the most practical way. 
     while(intsAssigned != 9){ 
      int currentColumn = 0; 
      Placer[currentColumn][0] = random.nextInt(20); 
      Placer[currentColumn][1] = random.nextInt(20); 
      Placer[currentColumn][2] = random.nextInt(20); 
      currentColumn++; 
      intsAssigned + 3; 

     } 
     printNumbers(); 

    } 

    //Print all of the index's 
    public static void printNumbers(){ 
     int numbersPrinted = 0; 
     int currentColumn = 0; 
     int currentRow = 0; 
     while(numbersPrinted != 9){ 
      System.out.println(Placer[currentColumn][currentRow]); 
      System.out.println(Placer[currentColumn][++currentRow]); 
      System.out.println(Placer[currentColumn][currentRow + 2]); 
      currentColumn++; 
     } 

    } 
} 
+0

是的,刚刚看到了。谢谢,现在编辑。还有什么区别? –

+0

你也似乎从不增加数字打印,所以虽然不会退出。相反,currentColumn将继续向上,直到超出范围 – StephenTG

+0

此外,currentColumn在循环内被初始化为0,所以无论什么时候使用,它都不会是0但是不是0 – StephenTG

回答

4

Placer是int[2][2] ...但您试图访问Placer[currentColumn][2]。对于大小为2的数组,只有两个索引可以访问:0和1.

也许你想要Placer成为int[3][3]

3

在Java索引基于零,这意味着数组:new int[2][2];将具有两行和两列,并且它们中的每将与0..1被索引。

一般来说,如果你声明和数组,例如ints:new int[n]你的索引应该从0到n-1(0,..,n-1)。多维数组也是这种情况。大小为m的每个维度将从0到m-1(0,..,m-1)索引。

0

它没有被初始化。

这里的阵列的示例

INT []×= {1,3}

总和= X [0] + X [1]。

+0

整型数组的默认值为0由语言规范保证: 创建时,每个类变量,实例变量或数组组件都被初始化为默认值(§15.9,§15.10)[...]对于int类型,默认值为零,那就是0.所以整个数组将被初始化为零。 如果你想初始化一个数组到一个不同的值,你可以使用java.util.Arrays.fill()(这当然会在内部使用一个循环)。 – user987339

1

intsAssigned + 3;不修改变量。你的意思是要做到这一点:

intsAssigned += 3; 

此外,这static int[][] Placer = new int[2][2];将创建长度 2的行和列,所以对于那些索引位置只会01

我想你想将其更改为:

static int[][] Placer = new int[3][3]; 

而且这个条件:while(numbersPrinted != 9)将永远是正确的,因为你永远不incrememnt numbersPrinted

1

除了什么dcsohl/user987339已经提到的,还有一堆的代码中的其他失误。

你永远不会增加数字打印,这样虽然不会退出。相反,currentColumn将继续向上,直到超出范围。只需在

numbersPrinted += 3; 

在第二个循环中增加currentColumn并且应该是固定的。

另外,currentColumn在第一个循环内被初始化为0,所以无论什么时候使用,它都不会是0。您应该移动

int currentColumn = 0; 

到第一次之前。

+0

Gotcha。谢谢,因为你可以probs告诉我是一个自学成才的新手;) –