Read standard input (stdin) with Scanner in Java

Since JDK 1.5 a popular way to read input from standard input (stdin) is using the Scanner class.

Scanner takes input from System.in which uses the InputStream class.

public class ReadConsoleInput {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter string:");
        String next = scanner.next();
        System.out.println("Enter int:");
        int nextInt = scanner.nextInt();
        scanner.close();

        System.out.println("String is: " + next);
        System.out.println("Int is: " + nextInt);
    }
}

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>