- Scanner
- BufferedReader and InputStreamReader
- Console
- DataInputStream (This is deprecated)
Scanner
This is the easiest way to get keyboard inputs from the user. Java Scanner class comes under the java.util package. Normally scanner tokenize the input from the white spaces as a default delimiter. An another advantage of the Scanner is you don't have to write another like to convert the value into a different (required) data format.
import java.util.Scanner; // Set the default input stream (keyboard) to the scanner object. Scanner scan = new Scanner(System.in); // Default next method returns you the value as a String. String s = scan.next(); // Use the nextInt(), nextDouble() like methods to read the input and parse that directly to a required data format. int i = scan.nextInt(); // Can read the whole line at once. String s = scan.nextLine();
Buffered Reader and Input Stream Reader
These two classes comes under the java.io package.
import java.io.BufferedReader; import java.io.InputStreamReader; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int i = Integer.parseInt(br.readLine());
Console
The Console class is also comes under the java.io package.
import java.io.Console; Console console = System.console(); String s = console.readLine();
No comments:
Post a Comment