Home > Software design >  "Variable name" cannot be resolved to a variable. Java
"Variable name" cannot be resolved to a variable. Java

Time:10-29

this is part of my code. I keep getting arrayAverage cannot be resolved to a variable and didn't manage to find any decent explanation of why?? Anyone can help?

import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;

public class ArrayDemo{

    public static void main(String[] args){

    int[] randomArray = initRandomArray();

    
    double arrayAverage = listAverage(randomArray);
    System.out.println(arrayAverage);

    }

    public static double listAverage(int[] randomArray){
        int total = 0;
        for (int i = 0; i < randomArray.length; i  ){
            total = randomArray[i]   total;
            double arrayAverage = total/randomArray.length;
        }
        return arrayAverage;
    }

CodePudding user response:

You need to declare it outside the for loop as follows:

public class ArrayDemo{

    public static void main(String[] args){

       int[] randomArray = initRandomArray();

       double arrayAverage = listAverage(randomArray);
       System.out.println(arrayAverage);
    }

    public static double listAverage(int[] randomArray){
        int total = 0;
        double arrayAverage = 0;
        for (int i = 0; i < randomArray.length; i  ){
            total = randomArray[i]   total;
            arrayAverage = total/randomArray.length;
        }
        return arrayAverage;
    }
}

The reason is that when you declare it inside the for loop its scope will be the for loop only, but you are trying to use it outside the for loop and after it is finished.

CodePudding user response:

The reason it can't resolve the variable is because of the scope. You declare arrayAverage within a for loop, and so that is all that that variable is defined for. You can think of it as the compiler deletes a variable as soon as it hits a closing }. In your case, arrayAverage is defined, then hits the end of the scope and is deleted. This happens every time the for loop runs until at the end, arrayAverage is deleted, and then you try to return it.

for (int i = 0; i < randomArray.length; i  ){
            total = randomArray[i]   total;
            double arrayAverage = total/randomArray.length; // create arrayAverage
        }                                                   // delete arrayAverage
        return arrayAverage;                                //arrayAverage doesn't exist anymore

To fix this, you have to change the scope of arrayAverage like João Dias suggested.

public static double listAverage(int[] randomArray){
        int total = 0;
        for (int i = 0; i < randomArray.length; i  ){
            total = randomArray[i]   total;
        }
        double arrayAverage = total/randomArray.length;
        return arrayAverage;
    }

This way when you return it, arrayAverage is in scope.

  • Related