我的问题是我不知道如何从同一个扫描仪行读取两个整数(用空格分隔)并验证它们都是整数,如果没有,则打印相应的错误消息并重新提示。当我输入两个非整数作为输入
时,这是一些如何打印错误消息的方法/**
* 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);
}
答案 0 :(得分:0)
您可以将其作为字符串读取,按空格分割并获取每个条目的值。