0

(我是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)

我似乎在类型转换方面做了一些明显错误的事情——但我一辈子都想不通。

4

1 回答 1

5

在这条线执行的时候

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

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

声明该字段

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

于 2013-09-03T17:43:22.180 回答