Lmnoppy Lmnoppy - 28 days ago 13
Java Question

double toString changes value to null - NullPointer Exception

I am trying to get values from Calculator in Prompter class, change them to strings and then display them when the welcome message is called. When i use toString method on the double values i get a nullpointer exception but dont understand why as i can see the values in the console (using the sys out in main)

So why is toString changing my values to null and what do i not understand?

Thank you for any help.

Main

public class Main {

public static void main(String[] args) {
Prompter prompter = new Prompter();
Calculator calculator = new Calculator();

System.out.println("pre " + calculator.getPreBrexitExchangeRate() + " post " + calculator.getPostBrexitExchangeRate());

prompter.welcomeMessage();

}
}


Prompter

public class Prompter {

private Calculator calculator;

private String mPreBrexitString = calculator.getPostBrexitExchangeRate().toString();
private String mPostBrexitString = calculator.getPreBrexitExchangeRate().toString();


public void welcomeMessage() {
System.out.println("Welcome message bla bla, pre-Brexit exchange rate is set as: " + mPreBrexit +
" and the current post Brexit rate is: " + mPostBrexit);
}


}


Calculator

public class Calculator {

private Double postBrexitExchangeRate = 1.22;
private Double preBrexitExchangeRate = 1.45;

public Double getPreBrexitExchangeRate() {
return preBrexitExchangeRate;
}

public Double getPostBrexitExchangeRate() {
return postBrexitExchangeRate;
}

}

Answer

You don't initialize calculator, without inisialization, the default value assigned will be null.

what you want is

    private Calculator calc = new Calculator();