我试图弄清楚为什么我的程序重复打印相同的语句。当我输入好的值时,我可以让这个方法正常工作,但是我设置了一个 else 语句来捕获无效的选择。当我的 else 语句运行时,它会无限打印并且 while 循环永远不会开始。我想不通。我将粘贴整个方法,但将问题区域加粗。我希望这很清楚。
public static int[][] placeCheese(int [][] gameBoard, String Player1Name)
{
Scanner console = new Scanner(System.in);
int turnTaker = 0;
int validRow = 0;
int validCol = 0;
int RowIndex = -1;
int ColIndex = -1;
while(turnTaker == 0)
{
while(validRow == 0)
{
System.out.println( Player1Name + ", please place your cheese by choosing a row, or choose -1 to exit.");
RowIndex = console.nextInt() -1;
if(RowIndex < gameBoard.length && RowIndex >=0)
{
validRow++;
}
else if(RowIndex == -2)
{
System.out.println("Thanks for playing, " + Player1Name + " has forfeited!");
System.exit(0);
}
}
while(validCol == 0){
System.out.println( Player1Name + ", please place your cheese by choosing a column, or choose -1 to exit.");
ColIndex = console.nextInt() -1;
if(ColIndex < gameBoard.length && ColIndex >=0)
{
validCol++;
}
else if(RowIndex == -2)
{
System.out.println("Thanks for playing, " + Player1Name + " has forfeited!");
System.exit(0);
}
}
if(gameBoard[RowIndex][ColIndex] == 0)
{
gameBoard[RowIndex][ColIndex] = 1;
turnTaker++;
numPieces1--;
}
else
{
System.out.println("this space is already occupied, please choose again.");
}
return gameBoard;
}