• Post Reply Bookmark Topic Watch Topic
  • New Topic

Scanner trouble  RSS feed

 
Vlad Trox
Greenhorn
Posts: 2
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello from Ukraine!

I have such simple task to read int values by Scanner

my input example: 1 5 3 7 2 6 3 6 7 4 2

I wrote such code:


My program must collect count of duplicated digits - I put them in HashMap.

Question: my programm fall in infinite loop, can somebody tell me what i'm doing wrong?
 
Knute Snortum
Sheriff
Posts: 4279
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Vlad Trox, and Welcome to the Ranch.

I believe that Scanner#hasNextInt() will always return true when it is opened to System.in.  I think the best solution is to use Scanner#nextLine() to read the entire line of numbers, then use String#split() to split the string into individual numbers.

Get that a try and see how it works.
 
Vlad Trox
Greenhorn
Posts: 2
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Knute Snortum! I try another way and it is works fine now!

 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:. . . I believe that Scanner#hasNextInt() will always return true when it is opened to System.in. . . .
No, it doesn't. Try it on an input like this:-
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is hasNext() or hasNextLine() that always return true.

And welcome to the Ranch again
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!