Here is a sample Java code to get keyboard input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.io.*; class Prompt { public static void main(String args[]) throws IOException { System.out.print("Input Something: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); System.out.print("You input: "); System.out.println(str); } } |
If you want to read user input successively, the following code will help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.*; class Prompt { public static void main(String args[]) throws IOException { while (true) { System.out.print("Input Something: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); System.out.print("You input: "); System.out.println(str); } } } |
This code will end if the user type Ctrl and D.
If you don’t want the user to type Ctrl and D, the following code is an alternative.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.*; class Prompt { public static void main(String args[]) throws IOException { while (true) { System.out.print("Input Something: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); if (str.isEmpty() || str.equals("exit")) { break; } System.out.print("You input: "); System.out.println(str); } System.out.println("Bye!"); } } |
Environment
I checked the above codes work in the following environment.
- OS: Windows 8
- JDK: 1.7.0_51