Handling input in a stand-alone Java program

Tutorial:

Handling input in a stand-alone Java program

By Cameron McKenzie

TheServerSide.com

We are going to look at three different ways of taking input from the user. The first way will be to use the Console class which is accessed through the System object. The readLine() method of the Console class takes input from the user at the command line and returns a String to the calling program. The nice thing about using this approach is that you don’t need to import anything because the System class is part of the ubiquitously available java.lang package. The drawback to using the Console approach is that it doesn’t typically work in IDEs like Ecliple and NetBeans. The Console can only be guaranteed to work if you’re running Java code directly on the JVM, so be warned.

System.console().readLine(); //takes input, returns a String

The second approach to garnering input from the user will be to use the Scanner class, which is found in the java.io package. Using the Scanner class is typically a two step process, although you can get cryptic and roll it all into one, long, strung out method call:

Scanner scanner =  new Scanner(System.in);
String input   =  scanner.next();

/* or String input   =  (new Scanner(System.in)).next(); */

Unlike the Console class, using the Scanner should work equally well both on the command line and within standard IDEs such as Eclipse and NetBeans.

The third method we'll look at for obtaining user input is the most fun. The JOptionPane, which is part of the javax.swing family of components, actually throws up a nice little input dialog box asking the user for input. The user’s input is then returned to the calling program as a String.

JOptionPane.showInputDialog("Rock, paper or scissors?");

To start off, take a look at our rather nascent Game.java class that simply prints out some sample text describing the Rock-Paper-Scissors game:

The Java class: Game.java

public class Game {

  public static void main (String args[]) {

    System.out.println("If I choose Rock,");
    System.out.println("And you choose Scissors,");
    System.out.println("Then I win and you lose!");

  }
}

Handling user input with System.console

To play around with the task of taking input from the user, we're going to write some code in the same file. Right after the close bracket of the Game class, add another class declaration for a non-public class named ConsoleGame that has a main method.

class ConsoleGame {

  public static void main (String args[]) {

  }
}

Within the body of the main method, prompt the user to type in either Rock, Paper or Scissors. Then use the System’s console class to obtain input from the user, and then echo the response back to the user telling them what they picked. It’s only three lines of code.

    System.out.println("Rock, Paper or Scissors?");

    String input   =  System.console().readLine();
    System.out.println("You chose: " + input);

When you’re done, the entire Game.java file will look like this:

public class Game {

  public static void main (String args[]) {

    System.out.println("If I choose Rock,");
    System.out.println("And you choose Scissors,");
    System.out.println("Then I win and you lose!");

  }
}

class ConsoleGame {

  public static void main (String args[]) {

    System.out.println("Rock, Paper or Scissors?");
    String input   =  System.console().readLine();
    System.out.println("You chose: " + input);

  }
}
/* WARNING: The Console may not work in IDEs such as Eclipse */

Use the javac utility to compile the Game.java file. When you do, notice that upon successful compilation, a new file named ConsoleGame.class appears in the bin directory of the JDK, along with the Game.class file.

With the Game.java file successfully compiled, you can now run the ConsoleGame class at the command line using the standard syntax. Here are the results I encountered when I ran the program and provided input:

C:\_jdk1.7\bin>javac Game.java

C:\_jdk1.7\bin>java  ConsoleGame

Rock, Paper or Scissors?

RoCK

You chose: RoCK

Multiple classes in a single Java file

The job of stuffing a second or third class in a Java file is not one you will perform too often, but it is a neat little trick that is allowable, with the only caveat being that each Java file can only have one public class, and that public class must exactly match the name of the Java source file that  contains it. But after that, you can have as many non-public classes within a Java source file as you wish. In fact, I’m going to add another non-public class named ScannerGame.

Handling user input with the Scanner class

Using the Scanner class, which is found in the java.util package, is relatively straight forward. An instance is created using the new keyword while passing the System.in InputStream to the constructor. With an instance of the Scanner class at your disposal, simply invoking the next() method will grab text from the user through the console window, bringing any text the user types out before hitting the return key into the program as a String. Here we hold that data in a String variable named input and simply echo that input back to the user:

class ScannerGame {

  public static void main (String args[]) {

    System.out.println("Rock, Paper or Scissors?");
    java.util.Scanner scanner = new java.util.Scanner(System.in);
    String input   =  scanner.next();
    System.out.println("You chose: " + input);
  }
}

Here is the interaction I get at the Java console when compiling and running the program. And remember, since this is in a file named Game.java, it is Game.java that gets compiled, while it is the ScannerGame class that gets run.

C:\_jdk1.7\bin>javac Game.java

C:\_jdk1.7\bin>java ScannerGame
Will it be Rock, Paper or Scissors?
PaPER
This time you chose: PaPER

Handling user input with a Swing component

Interacting with the Java Console is rather boring and un-intuitive. That's why I always like to break out a component in the Swing packages named JOptionPane. By simply calling the static method showInputDialog, and providing some prompting text as an argument, a graphical text box will appear to the user asking for input. Once they provide input and click the "OK" button, the text gets returned as a String to the calling program. 

The following SwingGame class, which is coded up in the 

class SwingGame {
 public static void main(String args[]) {

   String input = javax.swing.JOptionPane.showInputDialog("What will it be this time?");
   System.out.println("This time you said " + input);

 }
}

When the class is compiled and run, a simple dialog box appears asking for input, and the response from the user is echoed back in the console. It's not only simple and straight forward, but it's also a much more intuitive way to interact with the user.

 

09 Aug 2012

Related Content

Related Resources