3 ways for reading input from the user in the console
1. Using BufferedReader class
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. Here's an example:1 2 3 4 5 | BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); System.out.print( "Enter your name: " ); String name = reader.readLine(); System.out.println( "Your name is: " + name); |
2. Using Scanner class
The main purpose of the Scanner class (available since Java 1.5) 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. Here's an example:1 2 3 4 5 6 | Scanner scanner = new Scanner(System.in); System.out.print( "Enter your nationality: " ); String nationality = scanner.nextLine(); System.out.print( "Enter your age: " ); int age = scanner.nextInt(); |
- Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
- Regular expressions can be used to find tokens.
- The reading methods are not synchronized.
Read full article from 3 ways for reading input from the user in the console
No comments:
Post a Comment