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 + ".");
}
}
我在星号的两行上收到错误。它说numArray无法解析为变量,以及i。我使用eclipse作为我的IDE。
答案 0 :(得分:4)
do {
int i = 0;
int numArray[];
numArray [i] = keyboard.nextInt();
sum = sum + numArray[i];
i++;
} while (numArray[i] != -99);
numArray
在do while循环的范围内定义。所以你不能从范围之外访问它(也就是说你不能访问它,因为你试图在结束括号后访问它)。
要解决问题,请在周围范围内定义numArray
。
同样适用于i
。
答案 1 :(得分:0)
在do循环中定义numArray,因此它只在循环内可见。你需要在do之前将它(在其长度之外)初始化为do。
由于它看起来你的项目数量可变,我建议使用一个会根据需要增长的ArrayList。