Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Simple Java question

Name: OP 2010-04-20 0:00

trying to get a java program to read names with spaces in them. I know space is the default delimiter, and using next() will read only up to that. The solution is supposed to be to use nextLine() instead. My problem is that this completely skips the input, and just goes to the next lines of codes without giving any chance to input anything. My scanner is declared static, but I don't really see how this could be causing any problems, it's reading everything else fine.

All code related to this:

System.out.println("What is the name of this new member?(Include the tag)");
input = scan1.nextLine();
System.out.println(input);

System.out.println("What is this new member's age?");
ageinput = scan1.nextInt();

no chance to input for name, goes straight to input for age.

Name: Anonymous 2010-04-20 1:19

Name: Anonymous 2010-04-20 2:24

For one thing, you had better initialized that with System.in.

The problem you described occurs when there is still information in the stream that coincides with the requested Foo in the Scanner's nextFoo() method.  This is almost always the end of line character, which is what nextLine() uses as an implicit "delimiter."  For example, if you enter an integer value, you do "(integer)(Return key)" or "(int)(newline)."  nextInt() parses the "(int)" but the "(newline)" is still in the buffer and will be automatically retrieved if your next request is nextLine(), resulting in a blank input that does not wait for the user.

If this happens on the first input, I'm not sure what to make of it without more information.  Perhaps the newline character resulting from System.in.println(String) is erroneously being detected?

Name: Anonymous 2010-04-20 9:49

There was one previous input using the same scanner, using nextLine() after that worked. A fix I did earlier before their were any replies to this was have input = scan1.next(); then input += scan1.nextLine();
Never had problems with scanning and the new line character till now. Thanks.

Name: ​​​​​​​​​​ 2010-10-26 14:26

Name: Anonymous 2011-02-04 13:43


Don't change these.
Name: Email:
Entire Thread Thread List