-1
textfield2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent actionevent)
    {
        String input = textfield2.getText();
        Output2.setText("Your age is " + (2017-input));
    }
});

button2.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent actioneven)
    {
        String input = textfield2.getText();
        Output2.setText("Your age is " + (2017 -input));
    }
});

I am trying to get a number from the user (an integer) and subtract that number from 2017. It gives an error saying that it is a String and I can't subtract a number from a String. When I change String input to int input it gives errors again. It says that I can't use getText(). I've tried few ways such as parseInt() and it did not work. How can I fix this problem?

My Question is different from How to convert a String to an int in Java? because I looked at the answers there and they didn't really work with my code.

2 Answers2

1

You must convert the String obtained from the TextField to Integer

You can do that by

  • Integer.parseInt(string);
  • Integer.valueOf(string);

In you case you can do like this.

 Output2.setText("Your age is " + (2017 - Integer.parseInt(input)));

or

Output2.setText("Your age is " + (2017 - Integer.valueOf(input)));
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
1

You need to parse the input first before subtracting it

int input = Integer.parseInt(textfield2.getText());
Output2.setText("Your age is " + (2017 -input));
Sean Ervinson
  • 123
  • 3
  • 12