【发布时间】:2016-02-17 20:15:39
【问题描述】:
问题是我必须验证正确的输入,而我遇到的问题是仅验证整数输入(例如:如果他们输入字符或字符串,那就是问题)。那么问题是,如果我运行程序并且在第一轮它工作正常,但在第一轮之后它会打印出“两个输入必须是 0 到 2 之间的整数”。像 2 或 3 次然后允许重新进入。还添加了main方法。
/**
* Gets the position from the user of where the next move should be
* made. The board is then updated with a valid move
*
* @return true if there is a winner and false if there is no winner
*
*/
public boolean getMove()
{
boolean invalid = true;
int row = 0;
int column = 0;
//keeps asking for a position until the user enters a valid one
while (invalid)
{
row = -1;
column = -1;
System.out.println("Which row, column would you like to move to? Enter two numbers between 0-2 separated by a space to indicate position in (x,y).");
if (keyboard.hasNextInt())
{
row = keyboard.nextInt();
if (keyboard.hasNextInt())
{
column = keyboard.nextInt();
}
} else
{
keyboard.nextLine();
System.out.println("\nBoth inputs must be integers between 0 and 2.\n");
}
//check that the position is within bounds
if (row >= 0 && row <= 2 && column >= 0 && column <= 2)
{
//check that the position is not already occupied
if (board[row][column] != ' ')
{
System.out.println("That position is already taken");
} else
{
invalid = false;
}
} else
{
System.out.println("Invalid position");
}
}
//if it's currently X's turn then mark the space as char 'X' else 'O'
if (xTurn)
{
board[row][column] = 'X';
} else
{
board[row][column] = 'O';
}
//fill in the game board with the valid position
return winner(row, column);
}
【问题讨论】:
标签: java arrays java.util.scanner tic-tac-toe