我正在对阵列进行练习,目前我正处于其中一个
的变体中问题: - 我目前陷入困境,我应该如何将加载方法的输入值输入到print方法的正确位置。该程序将编译,但只返回一个等于零的average1。感谢任何帮助,我只是不能使用arraylist
import java.util.Scanner;
public class ScoreSetNumber3
{
private int[] scores;
private static final int SIZE= 100;
private double average1;
Scanner keyboard = new Scanner(System.in);
public ScoreSetNumber3()
{
scores = new int[SIZE];
}
public void load()
{
System.out.println("Please enter scores");
double sum = 0;
for( int used = 0; used < scores.length; used++)
{
scores[used] = keyboard.nextInt();
if(scores[used] >= 0)
{
sum += scores[used];
}
else
{
System.out.println("End of Inputs");
double average1 = sum / used;
System.out.println("Average value of array elements is" + " " + average1);
break;
}
}
}
public double getAverage()
{
return average1;
}
public void print()
{
for(int used=0; used < scores.length; used++)
{
if(scores[used] > getAverage())
{
System.out.println(scores[used] + " Above");
}
else if(scores[used] == getAverage())
{
System.out.println(scores[used] + " EqualTo");
}
else
{
if(scores[used] < 0)
{
break;
}
System.out.println(scores[used] + " Below");
}
}
}
}
答案 0 :(得分:1)
那是因为你不将平均值保存到全局变量average1
而是保存到局部变量。这就是average1
返回的getAverage()
等于零的原因。
从
更改load()
方法中的以下行
double average1 = sum / used;
到
average1 = sum / used;