我制作了一个程序,您必须找到用户输入的10个整数的平均值,然后让程序告诉我用户输入的数量实际上高于平均值,然后实际打印出来数字。我有问题告诉我什么是高于平均水平和他们是谁。相反,在计算平均值之后,它只是在输出
中继续给我这样的东西平均值高于0 这些数字是:0
我做错了什么?
public class Average {
static Scanner keyboard = new Scanner(System.in);
static int sum = 0, aboveAverage;
static double average;
public static void main(String[] args) {
int[] listOfInt = new int[10];// 10 integers MAX
System.out.println("Enter " + listOfInt.length + " integers: ");
for (int count = 0; count < listOfInt.length; count++) {
listOfInt[count] = keyboard.nextInt();
}
for (int count = 0; count < listOfInt.length; count++) {
sum = sum + listOfInt[count];
}
average = sum / listOfInt.length;// sum divided by 10
System.out.println("Average: " + average);
if (aboveAverage > average);
System.out.println("There are " + aboveAverage+ " numbers above the average");
System.out.println("Those numbers are: " + aboveAverage);
}
}
答案 0 :(得分:4)
您的if
块以分号结束;你可以像这样修理它
if (aboveAverage > average) { //;
System.out.println("There are "+aboveAverage+" numbers above the average");
System.out.println("Those numbers are: " + aboveAverage);
}
修改强>
在审核其余代码时,我认为您确实需要(使用diamond operator <>
)
double average = ((double) sum) / listOfInt.length;// sum divided by 10
System.out.printf("Average: %.2f%n", average);
List<Integer> aboveAverage = new ArrayList<>();
for (int v : listOfInt) {
if (v > average) {
aboveAverage.add(v);
}
}
System.out.printf("There are %d numbers above the average%n",
aboveAverage.size());
System.out.printf("Those numbers are: %s%n", aboveAverage);
修改2
全部放在一起,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] listOfInt = new int[10];// 10 integers MAX
System.out.println("Enter " + listOfInt.length + " integers: ");
for (int count = 0; count < listOfInt.length; count++) {
listOfInt[count] = keyboard.nextInt();
}
int sum = 0;
for (int i : listOfInt) {
sum += i;
}
double average = ((double) sum) / listOfInt.length;
System.out.printf("Average: %.2f%n", average);
List<Integer> aboveAverage = new ArrayList<>();
for (int v : listOfInt) {
if (v > average) {
aboveAverage.add(v);
}
}
System.out.printf("There are %d numbers above the average%n",
aboveAverage.size());
System.out.printf("Those numbers are: %s%n", aboveAverage);
}
答案 1 :(得分:0)
System.out.print("How many numbers will you like to find the Average for:");
int values;
values = input.nextInt();
int counter = values;
int number;
int total = 0;
while (counter > 0) {
System.out.print("Please enter a number: ");
number = input.nextInt();
total = total + number;
counter = counter - 1;
}
average = ((double) total / values)
System.out.println("The Average is: " + average);