Chairperson and Program Coordinator for the Computer Science Technology Program at Dawson College Instructor and Program Consultant for the School of Extended Learning Computer Institute at Concordia University I have been passionate about programming since buying an Apple][+ in 1980. I paid the extra $450 to bring the RAM up to 48K! Ken has posted 16 posts at DZone. You can read more from them at their website. View Full User Profile

NetBeans in the Classroom: Console Input Using Scanners

05.30.2014
| 2399 views |
  • submit to reddit
Ken Fogel is the Program Coordinator and Chairperson of the Computer Science Technology program at Dawson College in Montreal, Canada. He is also a Program Consultant to and part-time instructor in the Computer Institute of Concordia University's School of Extended Learning. He blogs at omniprogrammer.com and tweets @omniprof. His regular columns about NetBeans in education are listed here.

I am old enough to remember commercial applications that had a console interface. My students have no experience with the console. When Java was introduced the era of such applications was over. Instead you used AWT, then Swing and now JavaFX. For the student starting out in programming these GUI frameworks add complexity they may not be ready for. Therefore I start my classes using console input and output.

Input can be divided into two categories. The first is values. The primitive types such as int and double are value types. As I explain it, a value is a something you can perform both mathematical and logical operations on. The second is strings. A string does not have a value in the mathematical sense. Instead it has a state. Therefore it cannot be used in a mathematical expression. State can be compared and so strings can be used is logical expressions such as determining if two strings are the same. If you are ordering strings then you can also determine if one string is greater or less than the other.

Java does not have any console input routines for values. To Java everything you type is a string. This has meant that for many years every Java textbook author provided a console input routine that could convert strings to values. Java 1.5 made all these routines redundant with the introduction of the Scanner class. I could now teach input without needing to go into detail about wrapper classes or the NumberFormatException in a standard approach.
/**
 * Ask the user for their weight
 */
public void inputWeight() {
    Scanner sc = new Scanner(System.in);
    System.out.print("Please enter your weight: ");
    int weight = sc.nextInt();
    System.out.println("Weight = " + weight);
}
There is a problem with this code. If the user enters a string that cannot be converted we get the NumberFormatException we want to avoid.



Scanner provides a solution with its ‘hasNext. . .’ methods. These methods determine if the user input can be converted to the target value. You can reject input and avoid the exception.

/**
 * Ask the user for their weight
 */
public void inputWeight() {
    Scanner sc = new Scanner(System.in);
    System.out.print("Please enter your weight: ");
    int weight;
    // Accept input and test to see if it’s an integer
    if (sc.hasNextInt()) {
       // Success, it was an integer so get it
       weight = sc.nextInt();
       System.out.println("Weight = " + weight);
    } else {
        // Failure so retrieve the input as a String
        String bad = sc.next();
        // Inform the user what went wrong
        System.out.println(bad + " cannot be converted to an integer");
    }
}
Now when you run the program you get the following for a good input.



This is what you get for a bad input.



I will return to numeric input in another article as you do not want a program to end when the user makes one mistake.

Character Input

To make my assignments more interesting I have the students create a menu from which they must choose an action. I like to use letters as the menu choice.



The problem is that there is no nextChar() method in Scanner. Instead you need to use next() which will accept anything that you enter.

public void displayMenu() {
    Scanner sc = new Scanner(System.in);
    System.out.println("Select an Account");
    System.out.println("A: Savings");
    System.out.println("B: Checking");
    System.out.println("C: Exit");
    System.out.print("Please choose A, B or C: ");
    String choice = sc.next();
    System.out.println("You chose: " + choice);
}

Which could result in the following:



The first improvement is to convert the string into a character. To do this the string must only be one character long. Rather than checking the length you can just extract the first character in the string using the String class charAt method.

 String choice = sc.next();
char letter = choice.charAt(0);
System.out.println("You chose: " + letter);
This will work and if you enter “a” you will get ‘a’. The problem now is that the case of the character you entered should not matter. This is easy to solve by adding one more method from String into the mix.

 char letter = choice.toUpperCase().charAt(0);
Almost perfect but since we are using string input the user can enter any string they want. So “bacon” will result in ‘B’. We also need some way to control the allowable letters. In this menu the choices are A, B and C.

The solution is to use the ‘hasNext’ method for ‘next’. Not the normal, no parameter version, but the version that takes a pattern. Pattern is a polite way of saying Regular Expression.



From https://xkcd.com/208/

Just as we did with integer input we first test the string that the user has entered. The regular expression will be the pattern that will be used to determine if the string is correct. This regular expression is probably the simplest one you can write. We want a single character, either upper or lower case and is one of the three allowable characters. Here it is:

[ABCabc]

The square brackets indicate that this is a character class expression that can match only a single character. What goes inside the brackets are the allowable characters, in this case A, B, C, a, b or c. Since these characters are adjacent in the ASCII/Unicode table they can also be written as a range.

[A-Ca-c]

Putting this all together we get a routine that will only accept a single letter.

public void displayMenu() {
    Scanner sc = new Scanner(System.in);
    System.out.println("Select an Account");
    System.out.println("A: Savings");
    System.out.println("B: Checking");
    System.out.println("C: Exit");
    System.out.print("Please choose A, B or C: ");
    char letter;
    if (sc.hasNext("[A-Ca-c]")) {
        String choice = sc.next();
        letter = choice.toUpperCase().charAt(0);
        System.out.println("You chose: " + letter);
    } else {
        String choice = sc.next();
        System.out.println(choice + " is not valid input");
    }
}
Now if you enter ‘a’:



But if you enter ‘aardvark’:



In my next article I will look at console input a bit more and I will introduce you to the Beethoven test.
Published at DZone with permission of its author, Ken Fogel.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)