I’m learning Java and testing basic input handling.
I wrote the following simple program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
if (number == 1){
System.out.print("T");
} else {
System.out.print("F");
}
}
}
The program works fine when I enter a number like 1 or 5.
However, if the user types a letter (e.g., g), the program crashes with:
java.util.InputMismatchException
If the user enters anything other than 1, I simply want the program to print f — even if the input is a letter — without throwing an exception or stopping the program.
Should I avoid using nextInt() and read everything as a string instead, or is there a better practice for this?
hasNextInt()?