HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

Java – Read typesafe input using Scanner class

By Lokesh Gupta | Filed Under: Java I/O

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 !!

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

Java IO Tutorials

  • IO – Introduction
  • IO – How it works?
  • IO – IO vs. NIO
  • IO – Copy Directory Recursively
  • IO – Delete Directory Recursively
  • IO – Create File
  • IO – Write to File
  • IO – Append to File
  • IO – Create Read Only File
  • IO – Read File to String
  • IO – Read File to Byte[]
  • IO – Read File Line by Line
  • IO – BufferedReader
  • IO – BufferedWriter
  • IO – Read/Write Properties File
  • IO – Read file from resources
  • IO – Read/Write UTF-8 Data
  • IO – Check if File Exist
  • IO – File Copy
  • IO – FilenameFilter
  • IO – FileFilter
  • IO – Create Temporary File
  • IO – Write Temporary File
  • IO – Delete Temporary File
  • IO – Read from Console
  • IO – Typesafe input using Scanner
  • IO – String to InputStream
  • IO – InputStream to String
  • IO – Password Protected Zip
  • IO – Unzip with Sub-directories
  • IO – Manage System Log Size
  • IO – Generate SHA / MD5

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap