【发布时间】:2014-01-28 19:52:16
【问题描述】:
我正在编写一个程序,它以 10 个浮点数作为输入,并显示数字的平均值,然后显示所有大于平均值的数字。我正在使用一种将双精度数组作为参数并返回数组中数据的平均值的方法。但是,我的问题是当我运行我的程序时,输出窗口完全是空白的。我认为这是因为我没有在我的方法中调用 main 方法。但是,我不确定如何编写该代码。谢谢你。
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
}
public double average(double[] number) {
Scanner scanner = new Scanner(System.in);
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
int numberIndex = 0;
int largerIndex = 0;
System.out.printf("Please enter 10 floating-point numberes.\nIf more than 10 values are entered, the numbers following 10 are ignored.\nIf less than 10 numbers are entered, the program will wait for you to enter 10.\n");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
sum += numberList[x]; //add up all inputs to find sum
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
numberIndex = 0;
largerIndex = 0;
numberList = new double[10];
largerList = new double[10];
continue;
}
}
for (int i = 0; i < number.length; i++) {
sum = sum + number[i];
double average = sum / number.length;
System.out.println("Average value of your input is: " + average);
System.out.println();
//return average;
if (x > average) {
largerList[largerIndex] = x; //add negative input to negativeList array
largerIndex = largerIndex + 1;
}
}
for (int i = 0; i < largerIndex; i++) {
System.out.println(largerList[i]);
}
return 0;
}
}
【问题讨论】:
-
public static void main(String[] args) { new Average().average(new double[10]); }
标签: java arrays for-loop methods main