user5152798
user5152798

Reputation:

What is wrong with my java array code?

   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.

Upvotes: 1

Views: 55

Answers (2)

KeV
KeV

Reputation: 2891

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.

Upvotes: 4

JP Moresmau
JP Moresmau

Reputation: 7403

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.

Upvotes: 0

Related Questions