so I am creating a TicTacToe game right now and don't really know how to handle anything else but a int. Let's say the user input is a string - the program would throw a error. I actually want it to catch it and say something like "this is not a number between 1 and 9". How can I do this?
int nextPlayerTurn= scan.nextInt();
while (playerPosition.contains(nextPlayerTurn) ||computerPosition.contains(nextPlayerTurn)
|| nextPlayerTurn>= 10 || nextPlayerTurn<= 0 ) {
System.out.println("Position already taken! Please input a valid number (between 1 and 9) ");
nextPlayerTurn= scan.nextInt();
If you use nextInt()
and user enters a String, InputMismatchException will be thrown.
This is a way to handle it:
try {
scan.nextInt();
}catch (InputMismatchException e) {
System.err.println("this is not a number between 1 and 9");
}
Note that you will have to reuse nextInt()
until the user enters an int
You can either use try catch
method or if else
conditions.
using if else
,
if(scan.hasNextInt()){
int nextPlayerTurn = scan.nextInt();
if(nextPlayerTurn < 0 || nextPlayerTurn > 10){
System.out.println("this is not a number between 1 and 9");
}else{
//do something
}
}else{
System.out.println("this is not a number between 1 and 9");
}
using try catch
,
try{
int nextPlayerTurn = scan.nextInt();
if(nextPlayerTurn < 0 || nextPlayerTurn > 10){
System.out.println("this is not a number between 1 and 9");
}else{
//do something
}
}catch(InputMismatchException e){
System.out.println("this is not a number between 1 and 9");
}
However, you can also use a method to check the InputMismatchException
.
Also check Exception Handling Java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.