Read Input From Console in Java using Scanner Example

The scanner can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

Scanner sc = new Scanner(System.in); int i = sc.nextInt();

As another example, this code allows long types to be assigned from entries in a file input:

Scanner sc = new Scanner(new File("inputs")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); }

The Scanner class implements Iterator and Closeable interfaces.

When you created and initialized java.util.Scanner, you can use its various read method to read input from the user. for String you can use nextLine(), To read integer numbers, you can use nextInt(). We can use nextFloat() to read float input, nextDouble() to read double input.

import java.util.Scanner; public class ReadInputUsingScanner { public static void main(String args[]) { Scanner console = new Scanner(System. in ); System.out.println("Please enter text : "); String name = console.nextLine(); System.out.println("Please enter the number"); int number = console.nextInt(); System.out.println("You entered : " + number); System.out.println("Bye"); } } output: Please enter text : hello Please enter the number 23 You entered : 23 Bye

In this article, we have seen Read Input From Console in Java using Scanner Example.