Loading

Java: Input

Input

This Java video tutorial examines how to handle the input of a single character in Java. To handle this simple input, we use the read() function shown here:

System.in.read();

In order to use the read() function, we must add "throws java.io.IOException" after main() like this.

public static void main(String[] args)
    throws java.io.IOException {

The "throws" statement is needed in order to compile the code, but we will not explain it yet. If you forget it, you will get an error message like this one.

Exception in thread "main" java.lang.RuntimeException:
    Uncompilable source code - unreported exception java.io.IOException;
    must be caught or declared to be thrown at
    javalesson7.JavaLesson7.main(JavaLesson7.java:20)

Let us take a look at the short example code below. This is the full program.

package test;

public class Test {

    public static void main(String[] args)
            throws java.io.IOException {

        System.out.println("Johannes Gutenberg invented "
                + "the printing press around 1450 AD.");
        System.out.print("Answer (t or f): ");
        char cAnswer = (char)System.in.read();
        System.out.println("Your answer is " + cAnswer);
        System.out.println("The correct answer is t");
    }
}

We begin by noting that we need the "throws" statement directly after main() and before the {, as we mentioned earlier. Then we give a statement and prompt the user for an answer. The line after that calls the read() function to get the users's input, which is then stored in the char variable "cAnswer." Notice that we put (char) before the word System; this is required because the value read in is actually an int, and we need to make it a char. Finally, we print the user's answer and the correct answer so that they may be compared.

Program Output 1

Once the program is compiled and runs, the user is prompted by the message shown above. Before the user can enter an answer, he must make sure that the output pane has focus. Focus is indicated by, presence of the cursor after the message "Answer (t or f):" is printed. The cursor is the thin, black, vertical line shown above. If there is no cursor, the pane is not in focus, and the input will not work. To switch the focus to the pane, the user can left-click the pane.

Program Output 2

Once the pane is in focus, the user can enter an answer by typing a letter and then pressing ENTER; it is necessary to press ENTER or the input will not be received. Once the input is entered, the final message is printed, as shown above. Note that in this program the input can be almost anything, and the program will not complain because there is no error checking. It will simply take the first character that is read, put it into the variable, and print it.