-1

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;
}
ratalata
  • 1
  • 3
  • 1
    String[] coef = null; this is causing the null pointer when you are trying to access the array at the index coef[0] – atish.s Oct 17 '20 at 09:54
  • Why have you defined the variable `String[] coef` inside the `toString()` method? You already have a `private int[] coef` field with the same name. – Progman Oct 17 '20 at 09:55

1 Answers1

2

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.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72