aspose file tools
The moose likes Beginning Java and the fly likes the weirdest problem i came across in java about scanner string Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "the weirdest problem i came across in java about scanner string" Watch "the weirdest problem i came across in java about scanner string" New topic
Author

the weirdest problem i came across in java about scanner string

amr talaat
Greenhorn

Joined: Sep 02, 2012
Posts: 19
look at this code

the problem is that when i complie it and run it this is the result

how many times do you want to enter your name and age

console input{ i type 2 for example}

enter your name
enter your age
{ console input : }

enter your name
enter your age
{console input: }



it overlooks the input for name every time looping

why is that ???


when i change name from String to int and change nextline to nextInt

it do fine

whats wrong there ???






Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 3039
    
    4

This is a pretty common problem with the Scanner. When you do the console input, you press the enter key, effectively adding a new line to the input. When you first read the number from the input you do nextInt(), which reads the number but not the new-line. You then ask for the nextLine(), and since there is a new-line waiting in the input stream it immediately returns (with an empty String). You next ask for a nextInt() which lets you input a number, after which you again press the enter key, which enters a new-line after the number, and again the number is consumed by nextInt() but the new-line is not so the process occurs over and over again.

What you need to do is add an additional nextLine() after each nextInt().


Steve
amr talaat
Greenhorn

Joined: Sep 02, 2012
Posts: 19
thanks very much this solve the problem
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: the weirdest problem i came across in java about scanner string
 
Similar Threads
Writing to a file
Two Problems Try catch and If
Best way to get user input
String input with exceptions
Why does cons remain equal to null?