How do I accept text input in a console application?
Author: Deron Eriksson
Description: This Java tutorial shows how to accept text input into a console application.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1


Page:    1 2 >

Standard input can be read via System.in in javaSW. For text input, you can wrap System.in in an InputStreamReader. To accept a line of text (indicated via the 'Enter' key on your keyboard), you can wrap the InputStreamReader in a BufferedReader, which can return a line of typed text as a String via its readLine() method.

The InputTest class prompts the user for a line of text, and then it displays the line of text. It continues to do this until the user types 'x' followed by 'Enter', at which time the application says 'Bye!' and then exits.

InputTest.java

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputTest {

	public static void main(String[] args) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			while (true) {
				System.out.print("Enter Some Text ('x' to exit):");
				String str = br.readLine();
				System.out.println("You just entered:" + str);
				if ("x".equalsIgnoreCase(str)) {
					System.out.println("Bye!");
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

The execution of InputTest is shown below.

InputTest execution

(Continued on page 2)

Page:    1 2 >