| Author |
Adding Strings
|
Alix Ollivier
Ranch Hand
Joined: Jun 04, 2012
Posts: 63
|
|
|
How can I add the values of numbers in a String together? For example, I want to get String "1" and String "2" to be added together to make another string with the value of 3. How?
|
"The most exciting phrase to hear in science, the one that heralds new discoveries, is not 'Eureka!', but 'That's funny...' "
- Isaac Asimov
|
 |
Greg Brannon
Bartender
Joined: Oct 24, 2010
Posts: 530
|
|
|
Use the Integer.parseInt() method to obtain the integer values of the String objects and then add them together.
|
Learning Java using Eclipse on OpenSUSE 11.2
Linux user#: 501795
|
 |
Alix Ollivier
Ranch Hand
Joined: Jun 04, 2012
Posts: 63
|
|
|
I am trying to gather input from several JTextFields, convert them into ints, then add them together, and turn the resulting int into a string so that I can display it in another JTextField. The problem with that is that if there is an empty space in the JTextField, ParseInt displays an error, and the program crashes. So, I was thinking of skipping the int conversion part.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32830
|
|
|
No, you have to convert it to an int. No two ways about it. You can use the String#trim() method to remove some whitespace, but you would do better to verify that the text is in the correct format; if they write 123 456 that is invalid and the user must enter a new number.
|
 |
Kemal Sokolovic
Bartender
Joined: Jun 19, 2010
Posts: 800
|
|
Alix Ollivier wrote:I am trying to gather input from several JTextFields, convert them into ints, then add them together, and turn the resulting int into a string so that I can display it in another JTextField. The problem with that is that if there is an empty space in the JTextField, ParseInt displays an error, and the program crashes. So, I was thinking of skipping the int conversion part.
You must use Integer.parseInt() on JTextField(s) content in order to do what you want.
Note that parseInt throws NumberFormatException if the input is not valid (the given string cannot be parsed into integer value), so you can use it to validate user's input before doing what you want to do with those integer values.
|
The quieter you are, the more you are able to hear.
|
 |
 |
|
|
subject: Adding Strings
|
|
|