getText() 方法不适用于整数


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));
    }
});

我正在尝试从用户那里获取一个数字(整数(并从 2017 年减去该数字。它给出一个错误,说它是一个字符串,我不能从字符串中减去一个数字。当我将String input更改为int input时,它会再次出现错误。它说我不能使用getText().我尝试了几种方法,例如parseInt(),但没有奏效。如何解决此问题?

我的问题与如何在 Java 中将字符串转换为 int 不同?因为我查看了那里的答案,它们并没有真正适用于我的代码。

必须将从文本字段获取的String转换为Integer

你可以通过以下方式做到这一点

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

在你的情况下,你可以这样做。

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

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

您需要先解析输入,然后再减去它

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

最新更新