Handling input in a stand-alone Java program

by Cameron McKenzie

Being able to handle input is a pretty fundamental aspect of any enterprise Java application. For stand-along Java applications, past mechanisms for handling input have been onerous and non-obvious. Here we look at three different ways to handle user input, and compare the ease of use of all three.

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.

Download this free guide

Download now: Java EE moves to the Eclipse Foundation

What are application developers and market analysts saying about Oracles decision to move Java EE to the Eclipse Foundation? What will this change? Find out here.

By submitting my Email address I confirm that I have read and accepted the Terms of Use and Declaration of Consent.

By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.

You also agree that your personal information may be transferred and processed in the United States, and that you have read and agree to the Terms of Use and the Privacy Policy.

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:

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.

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>javaConsoleGame

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 thatcontains 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:

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.

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.

0 comments

Register

Login

Forgot your password?

Your password has been sent to:

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy