In this example we will show two ways to read input from console in Java.The first way is relatively simple, requiring you to create a Scanner object with system.in as a parameter.The second way is to wrap system.in using BufferedRead.
Source Code
– Example (1)
package com.beginner.examples;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
//Create Scanner object
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter the string and exit:");
//Read a line of string
String line = scanner.nextLine();
if("exit".equals(line.toLowerCase())) {
System.out.println("Bye");
break;
}
System.out.println("Your input is : " + line);
}
}
}
Output:
Enter the string and exit:
I love java
Your input is : I love java
Enter the string and exit:
I love programming
Your input is : I love programming
Enter the string and exit:
exit
Bye
– Example (2)
package com.beginner.examples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class UseBufferedRead {
public static void main(String[] args) {
// Get a byte stream for keyboard entry
InputStream is = System.in;
// converts to character stream
Reader reader = new InputStreamReader(is);
// wrap Reader as BufferedRead
BufferedReader br = new BufferedReader(reader);
// We could also write it this way
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter the string : ");
String line = br.readLine();
System.out.println("Your input is : " + line);
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Enter the string :
I love programming
Your input is : I love programming
References
Imported packages in Java documentation: