Java Quick Tip: "Problems" with the Scanner Class


Sun added the Scanner class in the JDK5.0 version. They did not write all of the methods the way I would have (but who asked me??). There are some quirks to making it work correctly. The problem occurs when reading text input from the keyboard and whether the text has a space in it or not. In the answer for the StockDriver from module 2, note the code

  // ask for the Customer ID and store the answer in the variable named custNum  
  System.out.println("What is the customer's id?");  
  int custNum = scan.nextInt();  
  scan.nextLine();    // used to make the scanner class behave correctly   
  // ask for the name of the stock.Store the answer in the variable named type  
  System.out.println("What is the name of the stock?");  
  String type = scan.nextLine();  

In the third line, you see an extra scan.nextLine(). Comment this out and run the program. You will get the following Console output:

  What is the customer's id?  
  44  
  What is the name of the stock?  
  How many shares do you have?  

Note that it did not wait for the answer to the second prompt before making the third one. You could try using scan.next(); instead of scan.nextLine(); but it also has problems when the String has a space in it.

The problem lies in the newline character at the end of the line (when you hit the return key) and how the Scanner class does not handle it consistently (is it another token or not?) when reading text input. Sometimes you will see the problem and sometimes you will not.

When you will see the problem: The problem occurs when reading text input after reading another primitive type like a boolean, int, or double.

How to ALWAYS solve the problem:
1. Always use nextLine() instead of next() for reading text input.
2. Anytime you read a primitive and then want to read text, add a line of code

  scan.nextLine();   

3. Make certain to do step 2. even if it is in a loop where we read in a boolean at the bottom of the loop, and if they answer true, it goes to the top of the loop and reads the next String (a text input).

Comments

Want to help U's picture

Found a bug in the site layout(Horizontal menu bar),
Plz place your mouse on any menu link that has drop down, and remove your mouse swiftly from the drop down menu, u will find the visited menu remains same. May be a bug in css part, plz check, u can remove this comment, but mail me what corrections u have made.
Nice blog, thank you for sharing knowledge.