Results 1 to 4 of 4
- 03-23-2011, 09:02 AM #1
Scanner - obtaining strings from console with nextLine
Hello,
I'm a Java newbie having trouble reading strings with spaces in from the console.
Here is an example:
Java Code:import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter double: "); double d = input.nextDouble(); System.out.print("Enter string: "); String s = input.nextLine(); System.out.println("String is " + s); } }
This code skips obtaining the string and moves on to the last statement:
C:\> java Test
Enter double: 4
Enter string: String is
If I remove the section of code to obtain the double, the string is captured ok.
What am I doing wrong?! Can someone please help? Many thanks!
- 03-23-2011, 09:08 AM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
I believe you need to make this call before prompting for s,
try adding that and see if it works as expected.Java Code:input.nextLine();
- 03-23-2011, 10:54 AM #3
- 03-23-2011, 11:16 AM #4
Scanner.netxInt, nextDouble etc consume the next matching token (characters that can be interpreted as int, double etc) and leave the rest in the Scanner. that 'rest' includes the EOL (end of line) generated when you press <Enter>I don't know why
The first nextLine encountered consumes this EOL without waiting for further input, as there is a 'next line' already available.
db
Similar Threads
-
Problem Of Scanner Object with its method nextLine()
By Cluster Storm in forum AWT / SwingReplies: 12Last Post: 06-17-2010, 05:40 PM -
Strings made by scanner don't work with startsWith() method
By samza in forum New To JavaReplies: 13Last Post: 05-16-2010, 12:09 AM -
Using Scanner console for Graphics
By bensewards in forum New To JavaReplies: 3Last Post: 03-17-2010, 02:16 AM -
Reading a line from console using Scanner class
By Java Tip in forum Java TipReplies: 0Last Post: 01-18-2008, 11:52 AM -
Read from console (Scanner Class)
By hey in forum New To JavaReplies: 10Last Post: 12-11-2007, 10:11 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks