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

(Continued from page 1)

With JavaSW 1.5, you can use the Scanner class to wrap System.in, and call nextLine() on the Scanner object to read in a line of text. This is illustrated in InputTest2.

InputTest2.java

package test;

import java.util.Scanner;

public class InputTest2 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while (true) {
			System.out.print("Enter Some Text ('z' to exit):");
			String str = scanner.nextLine();
			System.out.println("You just entered:" + str);
			if ("z".equalsIgnoreCase(str)) {
				System.out.println("Bye!");
				break;
			}
		}
	}
}

The execution of InputTest2 is shown below.

InputTest2 execution

As you can see, I'm getting sleepy. Also, this class uses 'z' as the exit character rather than 'x'.

If you're using Java 6 (or later), you may want to consider using the Console API. It can simplify writing console applications. Using the Console, you can read in a line of text via the following.

Console console = System.console();
String something = console.readLine("Type something: ");

In addition, you can use C-style printf's for text formatting of output to the console. You can also use a Scanner in conjunction with a Console to accept other input types.

Scanner scanner = new Scanner(console.reader());

Since this tutorial is created using Java 1.5, I did not create a test class for the Console API.

We have covered three different methods for obtaining text input in a console application. The first method relied on Readers, the second method utilized the Scanner class, and the third method mentioned used the Java 6 Console class.

Page: < 1 2