Simple Console Input Tutorial

Throughout my tutorials I have used the print and the println methods extensively. These methods are part of a large set of standard classes that together make up the Java Class Library (JCL). This tutorial will teach you the most basic way to receive input from the console, the System.in.read() method. In order to use this method I will have to use some syntax for a concept called exception handling. Exception handling will be handled in great detail in future tutorials so you can ignore the syntax for now.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md JavaInRead
C:\Java>cd JavaInRead
C:\Java\JavaInRead>Notepad JavaInRead.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class SystemInRead {
    public static void main(String args[]) throws java.io.IOException {
        System.out.print("Please enter a single character:");
        char c = (char) System.in.read();
        System.out.println("You pressed: " + c);
    }
}

Now switch back to the command prompt (CMD) and type in Javac · JavaInRead.java and press Enter.
Now type in java JavaInRead and press Enter.


C:\Java\JavaInRead>Javac · JavaInRead.java
C:\Java\JavaInRead>java JavaInRead A
You pressed: A


Final thoughts

I will be using the system.in.read() method in many of my tutorials. The extent that I will be using it will be to retrieve a single character input from the console. That is why this tutorial is so short, I just want to introduce you to the method before I begin using it in my future tutorials. If you're like me, you may want to Google the method and learn more about the things that it is capable of. Go ahead if you like, but it is really not necessary. There are much better ways to receive input from the console, but most of them require a much greater understanding of the Java language. Other better methods will be covered in detail in future tutorials.


Tutorials