0

(I'm new to Java so please forgive my ignorance).

I have a very simple 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;
    }

}

When I call the 'getSplit()' method, the runtime crashes with a NullPointer exception:

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)

I seem to be doing something obviously wrong with the casting of types - but I can't for the life of me think what.

1 Answer 1

5

At the time this line executes

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

The fields Total and others have not been initialized by the constructor and have a default value of null. parseDouble() must throw a NullPointerException if its argument is null (I cannot verify this, it might also come from dereferencing).

Declare that field

private Double Split;

and do the assignment in the constructor

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

Advice: Java non-constant instance variables should start with a lowercase alphabetical character.

Sign up to request clarification or add additional context in comments.

8 Comments

Another advice: constructors should be public.
And variables, like your methods, should begin with a lower case letter according to the Java convention.
thank you - that solves my problem. Makes total sense once you say it like that... :) Thanks again!
@WillGill You are welcome. Please heed the advice given in the comments and follow Java conventions.
Speaking of capital letters - is there a difference between Double and double?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.