簡體   English   中英

線程“ main”中的異常

[英]Exception in thread “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;

我認為這是因為我循環不正確。 我無法找到解決方案,並且在三個不同的日子里用谷歌搜索了大約一個小時。

這不是全部的代碼,但這是我認為正在拋棄的部分。 預先感謝您對錯誤的任何幫助。 如果您需要完整的代碼,請告訴我。

編輯:沒關系,我想通了。

我必須在數組的初始聲明中添加1

在這種情況下,意味着改變

clearPath2D = new int[gridSize][gridSize];

clearPath2D = new int[gridSize + 1][gridSize + 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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM