【问题标题】:What's causing this Stack Overflow error when there is no infinite recursive method? [closed]当没有无限递归方法时,导致此 Stack Overflow 错误的原因是什么? [关闭]
【发布时间】:2020-01-19 20:49:19
【问题描述】:

我正在用 Java 制作一个国际象棋程序。我有一个布尔方法,它以两个ints 的形式获取用户想要将车移动到的位置,并根据车的当前行和列确定车是否可以移动到那里,使用 for循环。这里以其中一个循环为例。

int nc = col - 1;
    while (nc >= 0){
    moves.add(new Integer[]{row, nc});
    if (locals[row][nc] != null)
        break;
    nc--;
}

moves 是我在程序前面声明的一个 ArrayList。它存储了所有有效移动的列表,这是我用来实例化它的 for 循环之一。

问题是,每次我运行这段代码时,包含 add 方法的行都会被高亮显示为无限循环,并且代码不会运行。我做错了什么?

编辑:

这是软件向我显示的确切错误消息:

另外,我将发布该方法的全文。我不确定其中是否与我的问题相关,但它可能会有所帮助。

public boolean isValidMove(int r, int c){
        Piece[][] locals = Chess.getBoard();
        if (r < 0 || c < 0 || r > 7 || c > 7 || (locals[r][c] != null && locals[r][c].getWhite() == isWhite))
            return false;
        ArrayList<Integer[]> moves = new ArrayList<Integer[]>();
        int nc = col - 1;
        while (nc >= 0){
            moves.add(new Integer[]{row, nc});
            if (locals[row][nc] != null)
                break;
            nc--;
        }
        nc = col + 1;
        while (nc < 8){
            moves.add(new Integer[]{row, nc});
            if (locals[row][nc] != null)
                break;
            nc++;
        }
        int nr = row - 1;
        while (nr >= 0){
            moves.add(new Integer[]{nr, col});
            if (locals[nr][col] != null)
                break;
            nr--;
        }
        nr = row + 1;
        while (nr < 8){
            moves.add(new Integer[]{nr, col});
            if (locals[nr][col] != null)
                break;
            nr++;
        }
        for (Integer[] ints : moves){
            if (ints[0] == r && ints[1] == c)
                return true;
        }
        return false;
    }

【问题讨论】:

  • 循环真的无限运行吗?
  • 您使用的是 IDE 吗? IntelliJ Idea 通常会在您编写代码时检测到诸如无限循环之类的事情并提供解决方案。当您将下划线悬停时,您的 IDE 会告诉您什么?
  • 我建议您从问题中删除不相关的代码和信息,并且只包括您认为存在无限循环的sn-ps。为了让问题更清楚。
  • 你试过在调试器中运行你的代码吗?
  • @ap 请在您的问题中发布运行时错误。

标签: java for-loop arraylist stack-overflow infinite-loop


【解决方案1】:

我发现了程序的问题并设法修复它。所讨论的循环实际上并不会永远迭代,但是该程序中某处的方法称为另一个方法,该方法又称为原始方法。因此,没有任何 one 无限递归方法的 Stack Overflow 错误。

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多