Console Input
Starting in Java 5, a built in class to take input was incorporated. This class is called the Scanner class and takes care of the back end intricacies of input and creates a simple way to get console information from a user. To use the Scanner class you must create a Scanner variable. Scanner variables are reference type variables, so they need to be declared and instantitated. When instantiating a Scanner variable, System.in must be passed as a parameter so that the Scanner knows to read from the keyboard. Also, there is an import required in order to use the Scanner class. So, programs that need to take user input will begin as follows:
import java.util.Scanner;
public class Input{
public static void main(String [] args){
Scanner reader=new Scanner(System.in);
...remainder of program follows
The variable reader in the program above can be named anything the programmer desires, as long as they follow the Java language rules for naming identifiers. Other options that are often used are input, io, read, etc.
The following methods are part of the Scanner class:
- nextInt(); //returns an int
- nextDouble(); //returns a double
- nextBoolean(); //returns a boolean
- nextLine(); //returns a String, terminated by a newline
- next(); //returns a String, terminated by whitespace
At a basic level, Scanner input would look like this:
System.out.println("Enter your age:");
int age=reader.nextInt(); //use next Int because the age variable is an int
System.out.println("You are "+age+" years old.");
Since there is no method to read a character variable, we have to read a string and find the character at its first spot.
System.out.println("What is your first initial?");
char initial=reader.nextLine().charAt(0);
There is a problem with the Scanner class that can be easily fixed. The issue comes in how the object reads from the stream. When an integer or double is read, the Scanner object reads the next number until it encounters whitespace (space, tab, return, etc). If we are reading multiple number consecutively, no problem. But, if we read a number followed by a string - big problem. What happens is the program will read the number and leave the users return on the stream. So, when it goes to read the nextLine(), it first finds the return character and stores nothing in the String variable. This can be fixed with a dummy read - a call to read input that is not stored in a variable.
System.out.println("Enter your age:");
int age=reader.nextInt();
reader.nextLine(); //dummy read to take the return off the stream
System.out.println("Enter your name:");
String name=reader.nextLine();
This practice is only necessary when you are going to take a String AFTER you have read an integer or Double.
Dialog IO (Optional)
Output can also be sent to the screen using a GUI dialog box called a message box. This message box is part of thw swing package in a class called JOptionPane, so be sure to import javax.swing.JOptionPane when trying to use this type of output. The method needed is called showMessageDialog and it takes four parameters:
- Component parentComponent - identifies the parent of the dialog box. we will always write null for this parameter
- String text - this is the actual output. The message that you want to send to the user.
- String title - this is the title for the message box. It must be in quotes.
- int icon - an int value that represents the icon that will appear in the box. JOptionPane has several constant variables that represent the different icons. They are listed below:
- JOptionPane.ERROR_MESSAGE - error icon
- JOptionPane.INFORMATION_MESSAGE - info icon
- JOptionPane.PLAIN_MESSAGE - no icon
- JOptionPane.QUESTION_MESSAGE - question icon
- JOptionPane.WARNING_MESSAGE - exclamation point icon
A typical call to show a message dialog box would look like this:
JOptionPane.showMessageDialot(null, "output information", "Box Title", JOptionPane.INFORMATION_MESSAGE);
JOptionPane also allows for easy dialog input in three formats: showInputDialog, showConfirmDialog, showOptionDialog.
The showInputDialog method takes only 1 parameter, the string prompt. It always returns a string, so information that needs to be treated as a number must be parsed. An example of the showInputDialog method is as follows:
int num =Integer.parseInt( JOptionPane.showInputdialog("Enter a number:"));
The showConfirmDialog allows the programmer to ask a simple yes/no questions. In its simplist form, there are three buttons: Yes, No and Cancel. This dialog returns an integer, 0 for yes, 1 for no and 2 for canel. This way, programmers can account for users not givein appropriate input by liminteg their choices. This method takes two parameters, the parentComponent (always null) and the string prompt. An example of the code is as follows:
int choice=JOptionPane.showConfirmDialog(null, "Would you like to continue?");
There are more advanced versions of the method available that allow programmers to show icons on the dialog and/or change the labels on the buttons.
The showOptionDialog method is the most versitile, and most complicated, of the dialog input choices. This method allows users to sepcify what type of input they want to take and it can be adapted to fit many needs. The method takes eight parameters and returns an int value of the button that is selected (starting at 0). The parameters are:
- Component parentComponent - usually null
- String dialogText - the question to be asked
- String dialogTitle - the title of the dialog box
- int buttonSet - the type of buttons in the box, typically JOptionPane.YES_NO_OPTION
- int icon - see the dialog output icon options
- null
- String [] options - the text for the buttons
- String default - the default selected/highlighted button
An example of the showOptionDialog method is as follows:
String [] buttons = {"Male", "Female", "Undecided"};
int choice = JOptionPane.showOptionDialog(null, "Are you male or female?", "Choice", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, buttons, buttons[0]);