Java – Read typesafe input using Scanner class

Learn to read typesafe user inputs from console in any interactive java application i.e. prompt the user until user inputs the value in correct format/datatype.

Table of Contents

Type unsafe way of reading input [Not recommended]
Typesafe way of reading input from console using Scanner [Recommended]

Type unsafe way of reading input

Ever tried using Scanner class to read user’s input in your interactive console based program? It’s very simple code to write. You asks the user a question and user input the value and press ENTER. Then you read the value using Scanner.nextXYZ() methods.

Let’s see an example for reading input from console using Scanner class.

private static void typeUnsafeReadExample() {

	Scanner scanner = new Scanner(System.in);

	System.out.print("Enter your age as an integer > ");
	
	int age = scanner.nextInt();
	System.out.println("Your age is " + age);
	
	scanner.close();
}

//Output - 1
Enter your age as an integer > 10
Your age is 10

//Output - 2
Enter your age as an integer > ten
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:864)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at com.howtodoinjava.examples.TypeSafeInputExample.typeUnsafeReadExample(TypeSafeInputExample.java:19)
	at com.howtodoinjava.examples.TypeSafeInputExample.main(TypeSafeInputExample.java:9)

As the user typed the correct input based on his understanding, but it crashed the application because of InputMismatchException exception.

Let’s solve this usecase.

Typesafe way of reading input from console using Scanner

Theoretically, we can make our program more robust by checking, before we read, that the next token matches our expected input. Scanner.hasNextXYZ() method does the exact thing, we needed here. It return true if the next token can be read as the data type requested.

For example, if we are expecting integer value then calling Scanner.hasNextInt() will return true only if next available token in scanner can be parsed as integer value. Else it will return false and we can notify the user that the value typed is not valid and re-prompt for new input.

Let’s see above solution using code.

private static void typeSafeReadExample() 
{
	Scanner scanner = new Scanner(System.in);

	System.out.print("Enter your age > ");

	while (!scanner.hasNextInt()) 
	{
		scanner.nextLine();	//clear the invalid input before prompting again
		System.out.print("Please enter your age in natural positive number > ");
	}

	int age = scanner.nextInt();
	System.out.println("Your age is " + age);
	
	scanner.close();
}

//Output:

Enter your age > ten
Please enter your age in natural positive number > 10.5
Please enter your age in natural positive number > 10
Your age is 10

Using Scanner.hasNextXYZ() and Scanner.nextXYZ() methods, we can write any console based interactive java application where we can force the user to enter valid inputs only – without crashing the program.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Java – Read typesafe input using Scanner class”

  1. The article above introduces us to read typesafe user inputs from the console in any interactive java application i.e. prompt the user until the user inputs the value in the correct format/datatype. I am sure this will help any amateur or beginner specializing in this field.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.