2013-03-21 95 views
0

好吧,基本上,我有一個多維數組,Board [8] [8]。我試圖在數組內使用隨機值並使其成爲不同的值。我正在改變的價值必須已經是一定的價值。我正在運行的代碼保持這些結果:更改二維數組中的值

java.lang.ArrayIndexOutOfBoundsException: 8 
     at checkers.init(checkers.java:32) 
     at sun.applet.AppletPanel.run(Unknown Source) 
     at java.lang.Thread.run(Unknown Source) 

這是導致問題的代碼。注意第8行是一個變量聲明:

int BLACK = 1;

Random generator = new Random(); 
    int checkersCount_B = 0, checkersCount_W = 0, x, y; 

    while(checkersCount_B < 9){ 
     x = generator.nextInt(9); 
     y = generator.nextInt(9); 

     if(Board[x][y] == BLACK){ 
      Board[x][y] = BLACK_CHECKER; 
     // System.out.println(x + " " + y); 
      checkersCount_B ++; 
     } else{ 
      //nothing 
     } 
    } 

第32行是if語句。

該代碼適用於幾個運行while循環,但從來沒有使過去兩三年,任何建議?

+0

這裏是關於一個更深入的描述爲什麼數組是0索引:http://developeronline.blogspot.com/2008 /04/why-array-index-should-start-from-0.html – 2013-03-21 20:45:05

回答

4

數組的索引從0到7. 迭代while(索引< 9),將取第9個元素(由索引8給出)。

+0

謝謝,這是那些日子裏的一個......你剛剛救了我幾個小時 – 2013-03-21 21:46:01

0

您正在使用generator.nextInt(9)生成從0到8的數字。由於電路板的寬度和高度爲8,因此您應該生成範圍從0到7的索引。將您的nextInt調用中的9更改爲8。

0

在陣列的索引從0(不是1)啓動,以便爲8個元素的陣列,你將不得不使用索引從0到7

1

你會跑出陣列中的一個的端部,因爲最終nextInt將返回8,但您的數組的索引是0-7(長度8)。

使用generator.nextInt(8)爲0和7之間返回一個隨機數

0

指數從0到7去;因此,您必須在該範圍內生成一個值。長度,但是,是8

0

複製和pasteable溶液:

Random generator = new Random(); 
int checkersCount_B = 0, checkersCount_W = 0, x, y; 

while(checkersCount_B < 8){ 
    x = generator.nextInt(8); 
    y = generator.nextInt(8); 

    if(Board[x][y] == BLACK){ 
     Board[x][y] = BLACK_CHECKER; 
    // System.out.println(x + " " + y); 
     checkersCount_B ++; 
    } else{ 
     //nothing 
    } 
}