0

I just started Java programming. I am trying to create a class method that will use an array in the same class in a for loop. But a NullPointerException is thrown when I try to run the program. Could anyone please point out what is wrong here? Thank you!

public class Judge {
    double [] judgeScoreArray;
    double judgeMean = getMean();
    //Method to calculate mean of an array
    public double getMean(){
        double sum = 0;
        //***NullPointerException Thrown at the next line***
        for (int i = 0; i <judgeScoreArray.length; i++){ 
        sum = sum + judgeScoreArray[i];
        }
        return sum/((judgeScoreArray.length));
    }

    public Judge(){
    judgeScoreArray = new double [7];
    for (int i = 0; i < 7; i++){
        judgeScoreArray[i] = 0;
    }
}
  • double [] judgeScoreArray; is never equal to something. It is always null. – Dainius Šaltenis Jan 23 '16 at 19:54
  • But I did initialize all the elements in the constructer. Does that make a difference. – Xiaocheng Yang Jan 23 '16 at 19:57
  • The for loop, where your error is thrown, is in no function. Please, edit the code. – Dainius Šaltenis Jan 23 '16 at 20:00
  • Sorry about the confusing layout. I spaced out the code. The for loop is part of the getMean() function. I hope that helps clarify the situation. Thank you. – Xiaocheng Yang Jan 23 '16 at 20:08
  • double judgeMean = getMean(); this line is runned before the constructor, so your judgeScoreArray is equal to null at that time. Leave the declaration (double judgeMean;), but initalize (judgeMean = getMean();) at the end of the constructor, just after the judgeScoreArray is being initalized and that should fix the problem. Sorry, I did not see that function before due to a layout. – Dainius Šaltenis Jan 23 '16 at 20:11
  • Got it! It worked! Thank you so much for your patience Dainius! I appreciate it! – Xiaocheng Yang Jan 23 '16 at 20:15

0 Answers0