• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with parsing integers from a string  RSS feed

 
Nadee Anders
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys, basically I'm trying to create a program that loops indefinitely until the user enters "exit" for the input. Except whenever I enter anything other then an integer value, the program will throw a NumberFormatException error. I'm a little unsure why this is because it shouldn't parse anything except the integer part of the input...which is why I don't understand why the code doesn't exit smoothly.

Any ideas?

 
vanlalhmangaiha khiangte
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int year = Integer.parseInt(line);

This line will throw that exception if other than number is entered ...

Hope this helps ..
 
Nadee Anders
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey thanks for the reply, yeh I'm aware what's causing the error, but am unsure why. What other procedures are there to handle the case when the user enters 'exit' then?
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use == false. Use while (!line.equals("quit")).

The problem is that you have got entry for the line before you parse it; if you happen to enter "quit" then it will try to get an integer out of "quit." You need to find a way to get the line and test it before trying to get an int out of it.

I shall refer you back to an older post where somebody seemed to find it hard to get a while loop to work, in that case looking for "stop." Try here. There is unfortunately a lot to read, but copying what Robin Lane finally used might sort out your problem.
 
Nadee Anders
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahh thanks for better way of determining equality with that Boolean Campbell Ritchie, was hoping there was a better way for that.

I ended up just using exception handling, was the simplest solution.

Thanks again
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not a Boolean, but a boolean you are using there. The difference may appear pedantic, but in a case-sensitive language like Java it is very significant.

And what are you doing with Exceptions? It is usually not at all good to use exceptions for flow control.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!