In Java, there are three different ways for reading input from the user in the command line (console).
1.Using Buffered Reader Class
This method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line.
1 2 |
DataInputStream in = new DataInputStream(System.in); number = Integer.parseInt(in.readLine()); |
or
1 2 3 4 5 6 |
//Enter data using BufferReader BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // Reading data using readLine String name = reader.readLine(); |
2. Using Scanner Class
This is probably the most preferred method to take input. The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however it is also can be used to read input from the user in the command line.
1 2 3 4 5 6 7 8 9 10 |
Scanner scan= new Scanner(System.in); String s = in.nextLine(); System.out.println("You entered string "+s); int i = in.nextInt(); System.out.println("You entered integer "+i); float f = in.nextFloat(); System.out.println("You entered float "+f); |
3. Using Console Class
It has been becoming a preferred way for reading user’s input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used (like System.out.printf()).
1 2 3 4 |
// Using Console to input data from user String name = System.console().readLine(); System.out.println(name); |