1
   import java.util.Scanner;


public class SumArray {

public static void main(String[] args) {


    int average = 0;
    int sum = 0;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter as many numbers as you wish. Enter -99 to finish your input.");



    do {        
        int i = 0;
        int numArray[];
        numArray [i] = keyboard.nextInt();
        sum = sum + numArray[i];
        i++;
    **} while (numArray[i] != -99);**

    **average = sum/numArray.length;**

    System.out.println("The sum of the numbers is " + sum + ".");
    System.out.println("The average of the numbers is " + average + ".");

}

}

I am getting an error on the two lines I asterisked. It says that numArray cannot be resolved to a variable, as well as i. I am using eclipse as my IDE.

2
  • 4
    Word for today is scope. Commented Jul 24, 2015 at 14:41
  • Declare the numArray variable outside the 'do' loop. And i. Commented Jul 24, 2015 at 14:46

2 Answers 2

4
do {        
    int i = 0;
    int numArray[];
    numArray [i] = keyboard.nextInt();
    sum = sum + numArray[i];
    i++;
} while (numArray[i] != -99);

numArray is defined inside the scope of the do while loop. So you can't access it from outside the scope (i.e. here you can't access it because you're trying to access it after the closing brace).

To solve the problem define numArray in the surrounding scope.

The same applies to i.

Sign up to request clarification or add additional context in comments.

Comments

0

You define numArray inside the do loop, hence it's only visible inside the loop. You need to initialize it (with its length) outside the loop, before the do.

Since it looks you have a variable number of items, I'd suggest using an ArrayList that will grow as needed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.