Java Reference
In-Depth Information
Console and Scanner Classes
Although Java gives you three objects to represent the standard input, output, and error devices, it is not easy to
use them for reading numbers from the standard input. The purpose of the Console class is to make the interaction
between a Java program and the console easier. I will discuss the Console class in this section. I will also discuss the
Scanner class used for parsing the text read from the console.
The Console class is a utility class in the java.io package that gives access to the system console, if any, associated
with the JVM. The console is not guaranteed to be accessible in a Java program on all machines. For example, if your
Java program is run as a service, no console will be associated to the JVM and you will not have access to it either. You
get the instance of the Console class by using the static console() method of the System class as follows:
Console console = System.console();
if (console != null) {
console.printf("Console is available.")
}
The Console class has a printf() method that is used to display formatted string on the console. You also have
a printf() method in the PrintStream class to write the formatted data. Please refer to Chapter 13 in Beginning
Java Fundamentals (ISBN: 978-1-4302-6652-5) for more details on using the printf() method and how to use the
Formatter class to format text, numbers, and dates.
Listing 7-41 illustrates how to use the Console class. If the console is not available, it prints a message and the
program exits. If you run this program using an IDE such as NetBeans, the console may not be available. Try to run
this program using a command prompt. The program prompts the user to enter a user name and a password. If the
user enters password letmein , the program prints a message. Otherwise, it prints that the password is not valid. The
program uses the readLine() method to read a line of text from the console and the readPassword() method to read
the password. Note that when the user enters a password, it is not visible; the program receives it in a character array.
Listing 7-41. Using the Console Class to Enter User Name and Password
// ConsoleLogin.java
package com.jdojo.io;
import java.io.Console;
public class ConsoleLogin {
public static void main(String[] args) {
Console console = System.console();
if (console != null) {
console.printf("Console is available.%n");
}
else {
System.out.println("Console is not available.%n");
return; // A console is not available
}
String userName = console.readLine("User Name: ");
char[] passChars = console.readPassword("Password: ");
String passString = new String(passChars);
if (passString.equals("letmein")) {
console.printf("Hello %s", userName);
 
Search WWH ::




Custom Search