• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

the weirdest problem i came across in java about scanner string

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ???






 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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().
 
amr talaat
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks very much this solve the problem
 
This is my favorite show. And this is my favorite tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic