• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adding Strings

 
Alix Ollivier
Ranch Hand
Posts: 71
Java Linux Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Greg Brannon
Bartender
Posts: 563
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use the Integer.parseInt() method to obtain the integer values of the String objects and then add them together.
 
Alix Ollivier
Ranch Hand
Posts: 71
Java Linux Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49841
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic