gpt4 book ai didi

java - 简单计算返回 NullPointer 异常...为什么?

转载 作者:行者123 更新时间:2023-12-01 17:21:17 25 4
gpt4 key购买 nike

(我是 Java 新手,请原谅我的无知)。

我有一个非常简单的类(class):

public class Bill {
private String Total;
private int Tip;
private int People;
Bill() {
Total = "0";
Tip=0;
People=0;
}
Bill (String total, int people, int tip) {
Total = total;
Tip = tip;
People = people;
}

//the problem is here somewhere.
private Double Split = (Double.parseDouble(Total) * ((double)Tip / 100)) / (double)People;

public String getTotal() {
return Total;
}

public double getSplit() {
return Split;
}

public double getTip() {
return Tip;
}

}

当我调用“getSplit()”方法时,运行时因 NullPointer 异常而崩溃:

09-03 19:37:02.609: E/AndroidRuntime(11325): Caused by: java.lang.NullPointerException
09-03 19:37:02.609: E/AndroidRuntime(11325): at java.lang.StringToReal.parseDouble(StringToReal.java:244)
09-03 19:37:02.609: E/AndroidRuntime(11325): at java.lang.Double.parseDouble(Double.java:295)
09-03 19:37:02.609: E/AndroidRuntime(11325): at williamgill.de.helloworld.Bill.<init>(Bill.java:21)
09-03 19:37:02.609: E/AndroidRuntime(11325): at williamgill.de.helloworld.DisplayMessageActivity.onCreate(DisplayMessageActivity.java:38)

我似乎在类型转换方面做了一些明显错误的事情 - 但我一生都无法思考什么。

最佳答案

执行该行时

private Double Split = (Double.parseDouble(Total) * ((double)Tip / 100)) / (double)People;

字段Total和其他字段尚未由构造函数初始化,并且具有默认值null。如果 parseDouble() 参数为 null,则必须抛出 NullPointerException(我无法验证这一点,它也可能来自取消引用)。

声明该字段

private Double Split;

并在构造函数中进行赋值

Bill (String total, int people, int tip) {
Total = total;
Tip = tip;
People = people;
Split = (Double.parseDouble(Total) * ((double)Tip / 100)) / (double)People;
}

建议:Java 非常量实例变量应以小写字母字符开头。

关于java - 简单计算返回 NullPointer 异常...为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18598381/

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