0

I have some JTextfields which change based on certain events, for example if a box is ticked, the content of the text field changes from 0 to 35.

I am trying to add the values of the text fields together but can't seem to do it.

int f1 = 35;
int f2 = 18;

apple.setText("" + f1);
pear.setText("" + f2);

Here's what I have so far

int result = Integer.parseInt(apple.getText() + Integer.parseInt(pear.getText());
                total.setText("" +  result);

The result gives me 3518 when I need it to add f1 and f2 together

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Paji.R
  • 155
  • 1
  • 1
  • 9

3 Answers3

2

What you're doing is concatenating two Strings first and then parsing the resulting String -- not what you want. What you want to do is to parse the text individually before adding them together.

try {
    int appleInt = Integer.parseInt(apple.getText());
    int pearInt = Integer.parseInt(pear.getText());

    int result = appleInt + pearInt;

    // do something with result

} catch (NumberFormatException nfe) {
    // warn user that text is wrong
    // clear text fields
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

You should do

int result = Integer.parseInt(apple.getText()) + Integer.parseInt(pear.getText());

Your code first convert the pear text into an Integer and sum it to the apple text String (int + String = String) and then the total is converted to an Integer but when summing the int with the String you only concatenated the two values; Instead you need to convert both the Strings to Integer and then sum them.

Don't forget to check if the values of the Strings are actually Integers or the program will throw a NumberFormatException.

aleb2000
  • 452
  • 4
  • 10
0

try this

int result = Integer.parseInt(apple.getText()) + Integer.parseInt(pear.getText());

instead of :

int result = Integer.parseInt(apple.getText() + Integer.parseInt(pear.getText());

Here I have actually individually parsed the apple.getText() and pear.getText() and then added the integers to get the result. Where as in the code you have uploaded you are basically concatenating apple.getText() with the Integer parsed value of pear.getText()

Blip
  • 3,061
  • 5
  • 22
  • 50