JAVA - 我如何保持增值

标签 java

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

例如,如果我将值 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/

相关文章:

java - 如何注入(inject)同一接口(interface)的多个模拟

java - 为什么会出现空指针异常?

java - SonarQube 吹毛求疵? - "Right curly brace and next "else"、 "catch"和 "finally"关键字应位于同一行"

java - Junit 测试 Map<String, List<String>> 的 java.lang.NullPointerException

java - 以 8 行打印列表 (java)

java - Selenium/Select Dropdrown/断言某个值是否存在

java - 如何将电话号码中的字符串关联打印为文本?

java - 如何使用Spring Boot批处理运行.bat文件

java - 为什么我无法在运行 JAR 之前加载所需的库?

java - Java Salesforce 应用程序中的 "Could not find the main class"