我正在尝试忽略任何非整数输入(例如r,$,£),并继续接受输入,直到有整数输入为止。任何帮助表示赞赏。
while (input.hasNextInt()){
int column = input.nextInt();
if (column < 0 || column > 6){
errorWrongInput();
continue;
}
if(placeCounter(board,column,player)) {
if (hasWon(board)){
System.out.println ("Player " +player+ " wins");
printBoard(board);
return;
}
player = playerTurn(player);
}
printBoard(board); // print the board
}
}
希望有帮助。如果没有,请在错过的地方做评论。
while (input.hasNext()){ // use hasNext instead of hasNextInt
try{
int column = input.nextInt();
if (column < 0 || column > 6){
errorWrongInput();
continue;
}
catch (InputMismatchException ex){ //catch Exception here for non integer input
input.next(); // do a next() here
continue;
}
if(placeCounter(board,column,player)) {
if (hasWon(board)){
System.out.println ("Player " +player+ " wins");
printBoard(board);
return;
}
player = playerTurn(player);
}
printBoard(board); // print the board
}
}