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

时间:2013-09-03 17:42:37

标签: java nullpointerexception

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

我有一个非常简单的课程:

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)

我似乎在做一些明显错误的类型的演员 - 但我不能为我的生活思考什么。

1 个答案:

答案 0 :(得分:5)

此行执行时

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

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

声明该字段

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非常量实例变量应以小写字母字符开头。