骑士旅游问题

时间:2017-01-23 20:27:30

标签: java

我正在尝试完成臭名昭着的" 骑士之旅"骑士必须围绕整个棋盘移动,直到它没有更多的选择或完成棋盘。我在" 运动"中遇到了不必要的越界错误代码,无法找出问题所在。感谢所有帮助!

import java.util.*;
public class Tour {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[][] board = new int[8][8];

    int rowpos = 1, vertpos = 1;
    board[0][0] =1;
    Random rand = new Random();
    int count = 1;
    for (int v=1; v<0;count++){

     int gen = rand.nextInt(8);

    if (gen == 0 && board[rowpos + 1][vertpos + 2] == 0){
        rowpos = rowpos + 1;
        vertpos = vertpos +2;
        board[rowpos][vertpos]=count;
    }
    if (gen == 1 && board[rowpos - 1][vertpos - 2] == 0){
        rowpos = rowpos - 1;
        vertpos = vertpos -2;
        board[rowpos][vertpos]=count;
    }
    if (gen == 2 && board[rowpos - 1][vertpos + 2] == 0){
        rowpos = rowpos - 1;
        vertpos = vertpos +2;
        board[rowpos][vertpos]=count;
    }
    if (gen == 3 && board[rowpos + 1][vertpos - 2] == 0){
        rowpos = rowpos + 1;
        vertpos = vertpos -2;
        board[rowpos][vertpos]=count;
    }
    if (gen == 4 && board[rowpos + 2][vertpos + 1] == 0){
        rowpos = rowpos + 2;
        vertpos = vertpos +1;
        board[rowpos][vertpos]=count;
    }
    if (gen == 5 && board[rowpos + 2][vertpos - 1] == 0){
        rowpos = rowpos + 2;
        vertpos = vertpos -1;
        board[rowpos][vertpos]=count;
    }
    if (gen == 6 && board[rowpos - 2][vertpos - 1] == 0){
        rowpos = rowpos - 1;
        vertpos = vertpos -1;
        board[rowpos][vertpos]=count;
    }
    if (gen == 7 && board[rowpos -2 ][vertpos +1] == 0){
        rowpos = rowpos -2;
        vertpos = vertpos +1;
        board[rowpos][vertpos]=count;
    }
    else{
        System.out.print("You moved " +count +" times.");
        break;
    }

}
}

}

1 个答案:

答案 0 :(得分:0)

即使有董事会外,您似乎也在检查职位。例如,以下行

if (gen == 0 && board[rowpos + 1][vertpos + 2] == 0) ...

会在vertpos >= 6rowpos == 7时抛出异常,这两种情况都是可能的。同样,

if (gen == 1 && board[rowpos - 1][vertpos - 2] == 0) ...
如果rowpos == 0vertpos <= 1

会引发异常

您需要通过在检查职位是否已被访问之前验证职位是否在董事会中来处理这些案件。

此外,您应该尝试重构代码,以减少重复性。如果您需要更多帮助,https://codereview.stackexchange.com/可能是一个好去处,但在获得其他人的帮助之前,请务必尽可能地完成它。