Java Reference
In-Depth Information
were needed. Experiment with this program.
E6. Suppose an array b[0..51] (or a Vector , or a String of 52 characters) con-
tains 52 values, e.g. it could be a deck of cards. Write a procedure that will “shuf-
fle” b . You can do this as follows:
1. Swap b[0] and b[i] , where i is a random integer in the range 0..51 .
2. Swap b[1] and b[i] , where i is a random integer in the range 1..51 .
...
51. Swap b[51] and b[i] , where i is a random integer in the range 50..51 .
5.7
Class JLiveRead for keyboard input
The core Java language has no facilities for reading from the keyboard or doing
other input/output (I/O). Instead, all I/O is provided in the classes in package
java.io . But these classes are very “low-level”, forcing you to deal with read-
ing one character at a time or a line of characters at a time, and then you have to
write methods for interpreting what those characters are.
JLiveRead of the CD ProgramLive makes reading from the keyboard easi-
er by providing static methods for reading integers, double values, and other
items. In this section, we show how to use the methods of this class.
When running a Java program, the letters you type appear in the Java con-
sole. So, reading from the keyboard is often called “reading the Java console”.
To use the methods of class JLiveRead , you have to place file
JLiveRead.java in the directory for the program and make sure that it is com-
piled as part of the project (it will be, if the project contains call on its methods).
Suppose you want to read into a variable s an integer that the user will type
on the keyboard. To do this, use the assignment statement:
Activity
1-5.2
Obtain class
JLiveRead
from a footnote
for this activity
on Lesson page
1-5.
// Read and store in s an integer typed by the user
s= JLiveRead.readLineInt();
When this statement is to be executed, execution waits until the user has typed
an integer and pressed the enter key; the typed characters are placed in the Java
console. As soon as the enter key is pressed, the integer that was typed is used as
the value of the expression JLiveRead.readLineInt() and assigned to s .
If the user types anything else besides an integer (preceding and following
whitespace is okay), an error message appears and the user is prompted to type
in an integer.
Prompting the user
Generally, the user will not know that they must type an integer until they
are told. We say that the user must be “prompted” for the input. So, when input
is needed from the keyboard, a program generally prompts the user for it.
(Actually, DrJava prompts automatically for keyboard input, but this is part of
DrJava and not of Java itself.)
Search WWH ::




Custom Search