0

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?

New contributor
Burak HINGE is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
3
  • 1
    Go look at your textbook and read up on try/catch blocks. Commented 2 days ago
  • 4
    Should I avoid using nextInt() and read everything as a string instead We don't really know what your further intentions are, but that would be one simple strategy, yes Commented 2 days ago
  • 2
    Are you aware of hasNextInt()? Commented 2 days ago

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.