aspose file tools*
The moose likes Beginning Java and the fly likes String to int Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String to int" Watch "String to int" New topic
Author

String to int

Maureen Charlton
Ranch Hand

Joined: Oct 04, 2004
Posts: 218
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Maureen Charlton
Ranch Hand

Joined: Oct 04, 2004
Posts: 218
Excellent - thank you very much

Thought there MUST have been an easier way!
(I always go the hard way route )
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
You may want to look at FormattedTextField in the javadocs (or maybe its JFormattedTextField, I can't remember).

Layne


Java API Documentation
The Java Tutorial
Nigel Browne
Ranch Hand

Joined: May 15, 2001
Posts: 673
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
 
Consider Paul's rocket mass heater.
 
subject: String to int