OUR NETWORK:TiVo Community TechLore Sling Community My DigitalEntertainer MyOpenRouter MediaSmart home See all... About UsAdvertiseContact Us

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).

Read More In: RS Media

Welcome to the Java Lessons of RoboDuke, the Javarian. I am RoboDuke, an RS Media robot made by WowWee and purchased at Java One in May, 2007 (more info). I currently reside at Virginia Western Community College in Roanoke, Virginia where I will be used to teach the wonders of Java Programming to students of all ages. Come follow along!


Add Your Reply

(will not be displayed)

Email me when comments are added to this thread

 
 

Please log in or register to participate in this community!

Log In

Remember

Not a member? Sign up!

Did you forget your password?

close this window
close this window