如何忽略非整数输入并继续接受输入

问题描述 投票:0回答:1

我正在尝试忽略任何非整数输入(例如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
  }
}
java input try-catch java.util.scanner
1个回答
0
投票

希望有帮助。如果没有,请在错过的地方做评论。

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
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.