Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String to int

 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am requesting some user input which is received as a String.
I wish to convert this to an int value.



No problems so far. But
When you enter the word seven and not 7 I get an exception error.

I want this to happen but what is the validation for this to happen?
Is it for example

If (numberOfStudents != Integer.parseInt(input1) )

Surely there must be an easier way?
Can't you say
If (numberOfStudents != int)?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You just have to catch the exception, and try again.



Another nicer option is to use a custom "NumericTextField" class in an input dialog; the NumericTextField class will only accept well-formed numbers, and your "OK" button would be greyed out otherwise. This is not terribly hard to do, but it's probably something that needs to wait until you get a bit more experience.
 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent - thank you very much

Thought there MUST have been an easier way!
(I always go the hard way route )
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may want to look at FormattedTextField in the javadocs (or maybe its JFormattedTextField, I can't remember).

Layne
 
Nigel Browne
Ranch Hand
Posts: 703
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Layne Lund:
You may want to look at FormattedTextField in the javadocs (or maybe its JFormattedTextField, I can't remember).

Layne


That'll be JFormattedTextField
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic