Some of the programs from the preceding lessons have not been written in the most efficient manner. To change any of the data values in the programs, it would be necessary to change the variable initializations, recompile the program, and run it again. It would be more practical if the program could ask for new values for each type of data and then compute the desired output.
However, accepting user input in Java has some technical complexities. Throughout this curriculum guide, we will use a special class, called ConsoleIO
, to make processing input easier and less tedious.
Just as the System class provides System.out
for output, there is an object for input, System.in
. Unfortunately, Java's System.in
object does not directly support convenient methods for reading numbers and strings.
To use the ConsoleIO
class in a program, you first need to import from the chn.util
package with the statement
import chn.util.*;
To use a ConsoleIO
method, you need to construct a ConsoleIO
object.
ConsoleIO console = new ConsoleIO();
Next, call one of ConsoleIO methods
int n = console.readInt();
double d = console.readDouble();
boolean done = console.readBoolean();
String token = console.readToken();
String line = console.readLine();
Here are some example statements:
int num1;
double bigNum;
String line;
num1 = console.readInt( );
bigNum = console.readDouble( );
line = console.readLine( );
When the statement num1 = console.readInt()
is encountered, execution of the program is suspended until an appropriate value is entered on the keyboard.
Any whitespace (spaces, tabs, newline) will separate input values. When reading values, white space keystrokes are ignored. If it is desirable to input both whitespace and non-whitespace characters, the method readLine()
is required.
The readToken()
method reads and returns the next token from the current line. A token is a String of characters separated by the specified delimiters (whitespace). For example when the following code fragment is executed
String input = console.readToken();
System.out.print(input);
when given an input line of
twenty-three is my favorite prime number
would output
twenty-three
since this is the first string of characters read before a whitespace value (space) is encountered.
When requesting data from the user via the keyboard, it is good programming practice to provide a prompt. An unintroduced input statement leaves the user hanging without a clue of what the program wants. For example:
System.out.print("Enter an integer --> ");
number = console.readInt();