从 java jtextfield 读取双精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20318748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:03:19  来源:igfitidea点击:

read in double from java jtextfield

javaswingdoublejtextfield

提问by lecardo

Seems like a very simple question however I can't read in a double from a jtextfield. I can easily read in a string using getText(); but no luck with double.

似乎是一个非常简单的问题,但是我无法从 jtextfield 中读取 double。我可以使用 getText() 轻松读取字符串;但没有运气双。

My objective is read in the double carry out a subtraction on it and then redisplay it back to the user once the submit buttons pressed...Action listener is working fine and to make it look more simple I didn't add it in...if it helps I can add it.

我的目标是在 double 中读取并对其进行减法,然后在按下提交按钮后将其重新显示给用户......动作侦听器工作正常,为了使它看起来更简单,我没有将它添加进去.. .如果有帮助,我可以添加它。

if (e.getSource() == submit)
            {
                cashRecieved = CashNeeded.getText();

            }

cashRecieved is type double therefore eclipse is complaining understandable stating it can't store a string to a double....

cashRecieved 是 double 类型,因此 eclipse 抱怨说它无法将字符串存储为 double 是可以理解的....

采纳答案by Vineet Kosaraju

You need to convert the String into a double. To do this, use the parseDouble method:

您需要将字符串转换为双精度。为此,请使用 parseDouble 方法:

cashRecieved = Double.parseDouble(CashNeeded.getText());

This returns type double (primitive), whereas valueOf returns type of the class Double.

这将返回 double(原始)类型,而 valueOf 返回 Double 类的类型。

EDIT:

编辑:

As Ingo mentioned, you should make sure you take care of the NumberFormatExceptions that occur when you try to parse an invalid string (eg: "Hello123") into a number.

正如 Ingo 所提到的,您应该确保处理在尝试将无效字符串(例如:“Hello123”)解析为数字时发生的 NumberFormatExceptions。

try {
    cashRecieved = Double.parseDouble(CashNeeded.getText());
} catch (NumberFormatException e) {
    e.printStackTrace();
    // handle the error
}

回答by Blub

double d = Double.valueOf(CashNeeded.getText());

You shouldn't capitalize variable names (I assume CashNeeded is one).

您不应该将变量名称大写(我假设 CashNeeded 是其中之一)。