my dog learned polymorphism*
The moose likes I/O and Streams and the fly likes delimiters and Scanner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "delimiters and Scanner class" Watch "delimiters and Scanner class" New topic
Author

delimiters and Scanner class

Steven Coddington
Greenhorn

Joined: Oct 17, 2004
Posts: 10
beginner programmer having trouble with Scanner and delimiters.

Here is the code that does not work:

import java.util.Scanner;

public class ScannerTester {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);

System.out.println("Enter a double ");
double d = s.nextDouble();
System.out.println("Your double is " + d);
System.out.println("enter some more text\n");
String thisString = s.nextLine();
System.out.println(thisString);
}
}

The problem is that there is no pause to input the string. The method apparently reads something without waiting for keyboard input. I tried changing the new Scanner line to

Scanner s = new Scanner(System.in).useDelimiter("\n");

without success.

Am I right that a delimiter other than default is needed? If so, which one?

Thanks


Steve Coddington
pete stein
Bartender

Joined: Feb 23, 2007
Posts: 1561
not quite. what you have to know is that a Scanner#nextDouble() will get the next token and return it if it parses into a well-formed double, but it does not eat the end of line mark. To do that, you should call scanner#nextLine() like so:
 
Don't get me started about those stupid light bulbs.
 
subject: delimiters and Scanner class
 
Similar Threads
Java noob -- sentinel-controlled while loop
Recompile with -Xlint:unchecked for details.
Java Methods code. Someone help please
err get and set methods and scanner class / JOptionPane
Scanners, Strings and doubles... Help!