please note that I'm a complete beginner to programming and have found learning Java quite hard. I have a school task that requires me to write a code for a toString() method and I've blindly followed what my teacher has been writing/teaching in class but for some reason my code doesn't seem to work when I run the test file? I've included my code below.
I do get an error that says the following- "Null pointer access: The variable coef can only be null at this location" but when I change all my coef[] variables, then my code becomes moot because it just equates to null.
Any pointers greatly appreciated!
EDIT 1: Thank you for your responses - I thought I needed to intialise coef[] as a variable inside my toString() method (big oops!!). Also thank you for providing the link to the NullPointer question - it had some really thorough explanations and now I understand that I dereferenced the coeff[]
variable.
QUERY a: I've removed my first line but now it seems that my code fails on this line return coef[1]+ "x + " + coef[0];
QUERY b: curious to know why it's a bad sign if the class is plural?
public class Polynomials {
public Double coefficient;
public Integer exponent;
private int[] coef;
public String toString() {
String[] coef = null;
if (exponent <= -1)
return "0";
else if (exponent == 0)
return "" + coef[0];
else if (exponent == 1)
return coef[1]+ "x + " + coef[0];
String s = coef[exponent] + "x^" + exponent;
return s;
}
Your Polynomials
class has 3 fields, and one is called coef
. In your toString method you then declare a local variable, also called coef
.
In java, that means the local variable 'shadows' the field - in other words, for that entire method, coef
refers to the String[] coef = null;
and not the int[] coef
.
And that local field is always null - you create it, initialize it to null, and never change it. Thus, choef[0]
will guaranteed throw a NullPointerException
at runtime.
The fix seems to be to .... just remove that String[] coef = null;
line entirely. I have no idea why you wrote that or what it's trying to accomplish.
NB: Shouldn't the class be named Polynomial
? Naming a class a plural is usually a bad sign.