2015-12-02 170 views
1

我不知道爲什麼我在我的範圍內不正確以及爲何引發此錯誤。線程「main」中的異常

在線程異常 「主」 java.lang.ArrayIndexOutOfBoundsException

private int gridSize = 3; 
private Point currentStep = new Point(0, 0); 
private Point firstStep = new Point(0, 0); 
private Point lastStep = new Point(gridSize, gridSize); 
private int pedometer = 0; 
private int random; 
private int down = 0; 
private int right = 0; 
private byte bottomReached = 0; 
private byte rightReached = 0; 
private int[][] clearPath2D; 

public void createWalk2D() { 

    clearPath2D = new int[gridSize][gridSize]; 
    for (currentStep = firstStep; currentStep != lastStep; pedometer++) { 

     step2D(); 

     if (rightReached == 1 && bottomReached == 1) { 
      break; 
     } 
    } 

    clearField(); 
} 

    public void step2D() { 

    random = stepRand.nextInt(); 

    // add a new step to the current path 
    currentStep.setLocation(right , down); 
    clearPath2D[right][down] = 4; 

    // calculates the next step based on random numbers and weather a side 
    // is being touched 

    if (currentStep.x == gridSize) { 
     rightReached = 1; 
     random = 1; 
    } 

    if (currentStep.y == gridSize) { 
     bottomReached = 1; 
     random = 0; 
    } 

    // decides the direction of the next step 
    if (random >= 0.5 && bottomReached == 0) { 
     down++; 
    } else if (random < 0.5 && rightReached == 0) { 
     right++; 
    } else if (rightReached == 1 && bottomReached == 1) { 
     done = true; 
    } 

} 

所以我所說的createWalk2D();然後我得到了錯誤和日食指向我的這一行代碼:

clearPath2D[right][down] = 4; 

我認爲這是因爲我在循環incorreclty。我一直無法找到解決方案,並在三個不同的日子裏搜索了大約一個小時。

這不是所有的代碼,但這是我認爲是拋棄它的部分。提前感謝您對錯誤的任何幫助。如果你需要整個代碼,請讓我知道。編輯: 沒關係我想通了。

我在這種情況下,以1添加到陣列

的初始宣佈它意味着改變

clearPath2D = new int[gridSize][gridSize]; 

clearPath2D = new int[gridSize + 1][gridSize + 1]; 
+0

自己調試代碼。在行'clearPath2D [right] [down] = 4'輸出到控制檯前的值爲'right','clearPath2D.length','down'和'clearPath2D [right] .length'。您的右側和下側值應始終小於數組的長度。 –

+0

'clearField();'做了什麼? –

+0

可能的重複[什麼導致java.lang.ArrayIndexOutOfBoundsException,以及如何防止它?](http://stackoverflow.com/questions/5554734/what-c​​auses-a-java-lang-arrayindexoutofboundsexception-and-how- do-i-prevent-it) – Raf

回答

1

你眼前的問題是在這部分代碼:

if (currentStep.x == gridSize) { 
     rightReached = 1; 
     random = 1; 
    } 

    if (currentStep.y == gridSize) { 
     bottomReached = 1; 
     random = 0; 
    } 

您應該針對gridSize-1進行測試,因爲這是最大有效索引。如在:

if (currentStep.x == gridSize-1) { 
     rightReached = 1; 
     random = 1; 
    } 

    if (currentStep.y == gridSize-1) { 
     bottomReached = 1; 
     random = 0; 
    } 
+0

感謝您的回覆!我想出了一個不同的方式,但我非常確定這種方式也能起作用 –

相關問題