Professional Documents
Culture Documents
4-1
public class CharacterInput { public static void main(String[] args) throws Exception { char charInput; System.out.print(Enter a character : ); charInput=(char)System.in.read(); System.in.read();System.in.read(); // absorbs the Enter key.
System.out.println(\nThe character entered is +charInput); } } In the above example, the string Enter a character prints on the screen. A message requesting user input is commonly known as a prompt because it prompts or coaches the user to enter an appropriate response. The System.in.read() is used to obtain a character
4-2
input entered by the user from the keyboard. The read() method accepts the returned integer into a character. The cast(char) converts the returned integer into a character. By default, the standard input is line buffered, so the Enter key must be pressed before any characters that we type will be sent to the our program.
There is, however, a problem when we use read() to accept a character from the keyboard, every key we press including the Enter key is accepted, one at a time. Thus, we can absorb the Enter key after each input by reading in with two read() method calls.
Since we are using the System.in.read() method, in the main() method header, a phrase throws Exception must be added at the end of the line. It is necessary to handle input errors. An exception is an error situation. Because errors should be infrequent, and all sorts of errors can arise, thus, we can let the compiler handle the problem by throwing the exception, or passing the error to the operating system. By placing throws Exception after the main() header accomplishes this and a program, which reads keyboard input will not be able to compile successfully without this phrase.
4-3
The example above shows the use of the readLine() method to allow the user to enter a string. Java implements I/O operations through streams. The streams are represented by two abstract classes, which include the InputStream and OutputStream. These classes are found in the java.io package. Thus, at the beginning of the program, the java.io package is imported into the program. To import an entire package of classes an asterisk(*) is used. It acts as wildcard symbol to represent all the classes in a package.
4-4
4-5
import java.io.*; public class IntegerInput { public static void main(String[] args) throws Exception { BufferedReader input = new BufferedReader(new InputStreamReader(System.in )); String numberOfstudent; int studNum;
System.out.println(Total is + studNum); } }
4-6
4-7
4-8
4-9