Thursday, 4 August 2011

Java: Input Statements

Second update, as promised! We've already looked at the output command, but certainly you'd like some interactivity with your program? What use is a program without a user? So we have input commands.

These are, however, more awkward to use than the output commands, so bear with it.

    static BufferedReader br = new BufferedReader(new InputStreamReader(;
    static String input = null;

    //The above 2 lines create the string to store the input into, as well as the buffered reader to 
    //actually read the input. Don't worry too much about the mechanics of this yet.

    public static String getInputStr() throws IOException {

        input = br .readLine();
        return input;


   // The above, from "public static..." to the closing curly brace is a function to more easily get the 
   // input later on in the code. We'll talk more about functions later, but for now, just know that
   // with this, we can type "getInputStr()" at a later point, and we will be given whatever's typed
   // into the standard input (keyboard).

With this bit of functionality, we can write a short program to take a user's name, then give a greeting to him or her.

System.out.println( "Please enter your name: " );
System.out.println( "Hello, " + getInputStr() + "! \nHow are you today?" );

This gives the output:

Please enter your name:
heddin (This is where I placed my input)
Hello, heddin!
How are you today?

No comments:

Post a Comment