gpt4 book ai didi

JAVA - 我如何保持增值

转载 作者:行者123 更新时间:2023-11-29 06:59:03 25 4
gpt4 key购买 nike

我有这个按钮和一个文本字段,我想在单击按钮时在变量上添加值,除了我无法向字符串变量添加值外,一切正常

例如,如果我将值 20 放在 tempvalue 字符串上,它应该有 20,我把 30 放在它应该有 50,但我得到的是 null2050。
我尝试了 += 运算符,但没有用。

没有任何运算符可以在其上不断增加值(value),还是我必须编写新方法?

private String tempvalue;

btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getTxt = textField.getText();
tempvalue += getTxt;

System.out.println(tempvalue);

}
});

最佳答案

您从文本字段中获取字符串。

String input = getTxt;

您必须将字符串解析为整数或任何其他数字类型。

int value = Integer.parseInt(input);

然后就可以进行计算了。

您还应该经常检查用户输入是否真的是一个数字。使用 try/catch 避免输入错误:

int value = 0;
int firstValue = 5; //example variable
try{
value = Integer.parseInt(input);
}catch(Exception e1){
System.out.println("Your input could not be parsed to a number");
}
int result = firstValue + value; //always be sure all your values are numbers and not strings
System.out.println("Result: "+result);

总计:

private int tempvalue = 0;

btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getTxt = textField.getText();
int value = 0;

try{
value = Integer.parseInt(getTxt);
}catch(Exception e1){
System.out.println("Your input could not be parsed to a number");
}

tempvalue += value;

System.out.println("Result: "+tempvalue);

}
});
}

关于JAVA - 我如何保持增值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29279338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com