我遇到一些我无法弄清楚的功课问题,如果有人能指出我正确的方向,我会非常感激。我的哨兵价值根本不起作用,我无法弄清楚它是否有效。我的平均值数组也是打印出来的内存位置,而不是值。这是我到目前为止的代码
public class DistanceFromAverage
{//Global Declaration Section
public static void main(String args[])
{//Declaration Section
double[] Numbers;
double[] Average;
//Input Section
Numbers = array_numbers();
//Processing Section
Average = distance_average(Numbers);
//Output Section
display_array(Numbers, Average);
}//end
public static double[] array_numbers()
{
double[] tmp;
tmp = new double[20];
double[] sentinel = {99999};
Scanner input = new Scanner(System.in);
int count = 0;
try
{
for (int i = 0; i < tmp.length; i++)
{
System.out.println("Please enter number");
tmp[i] = input.nextDouble();
}
}
catch(InputMismatchException exception)
{
System.out.println("A number must be entered");
System.exit(0);
}
return tmp;
}//end array
public static double[] distance_average(double[] Numbers) {
double sum = 0.0;
for (int i=0; i < Numbers.length; i++)
sum = sum + Numbers[i];
double average = sum / Numbers.length;
return new double[] {average};
} // determine average
public static void display_array(double[] Numbers, double[] Average)
{
for (int i = 0; i < Numbers.length; i++){
System.out.println("The numbers in the array are: " + Numbers[i] + "and the average is" + Average);
}
}//end display_array
}//end class
答案 0 :(得分:1)
关于打印为内存位置的平均值,
您的显示功能接受Average作为数组而不是简单的double。
这将在Array类上调用toString()。
由于平均值只是一个数字,因此在“System.out.println”语句中使用Average[0]
或在显示方法中接受类型为double的简单平均值,如下所示:
public static void display_array(double[] Numbers, double Average)
并更改
的签名public static double[] distance_average(double[] Numbers) {
到
public static double distance_average(double[] Numbers) {