wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Adding Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Adding Strings" Watch "Adding Strings" New topic
Author

Adding Strings

Alix Ollivier
Ranch Hand

Joined: Jun 04, 2012
Posts: 71

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: 557
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: 71

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: 38045
    
  22
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: 825
    
    5

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.
 
wood burning stoves
 
subject: Adding Strings
 
Similar Threads
Strings
equls/hashCode in MasterExam possible error
JAVAMAIL
Using Criteria API for many-to-many search
how to name and save the Television interface