Java – How to read input from console using Scanner

This example shows you how to read input from the console using the standard java.util.Scanner class.

JavaScanner.java

package com.mkyong.io;

import java.util.Scanner;

public class JavaScanner {

    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Please enter your name: ");
            String input = scanner.nextLine();
            System.out.println("name : " + input);

            System.out.print("Please enter your age: ");
            int age = scanner.nextInt();
            System.out.println("age : " + age);
        }

    }

}

Output


Please enter your name: mkyong
name : mkyong
Please enter your age: 38
age : 38

For scanner.nextInt(), if invalid input, it will throws java.util.InputMismatchException


Please enter your name: mkyong
name : mkyong
Please enter your age: 38wsss
Exception in thread "main" java.util.InputMismatchException
	at java.base/java.util.Scanner.throwFor(Scanner.java:939)
	at java.base/java.util.Scanner.next(Scanner.java:1594)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
	at com.mkyong.markdown.JavaTest.main(JavaTest.java:15)

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar