[hw] how to fix this "java.lang.NullPointerException"

Cheetoz

[H]ard|Gawd
Joined
Mar 3, 2003
Messages
1,972
Code:
public class Guess 
{
    double gOld[], gNew;
    String result = "";
    int i;
    
   double a = Math.random();
    
    Guess(double guess)
    {
        [COLOR="DarkOrange"]gOld[i]=guess;[/COLOR]
            
        while(Math.abs(gNew - gOld[i])>0.000000005)
        {   
            result = result + gNew + "\n";
            gNew = (Math.pow(gOld[i],2)-a)/2*gOld[i];
            i++;
            gOld[i] = gNew;
        }
    }

    public String toString()
    {
        return result;
    }
    

}

I am getting the error at orange part. I've read that the error means something could not initialized. But I don't see the error here. "i" is default at zero, so it should take the value "guess" and store it at index 0 of the array.
 
Looks like to me you never init int i so gOld is throwing a null pointer error.
 
yea, i just played with it in Eclipse. You need to give your array a size. I didn't even notice that.
 
even if i defaults to 0 if not specified, it is always good practice do explicitly define your variables.
 
But its not the problem of defining i, sickwookie was correct in saying that he never instantiates gOld.
 
yes, having seen that the answer was provided, i merely offered a suggestion for good practice.
 
Back
Top