Java 如何在下面的代码中为每个循环添加2个?
我需要写一个程序,把10个浮点数作为输入 程序应显示数字的平均值,后跟大于平均值的所有数字 我的部分需求包括编写一个方法,该方法将一个double数组作为参数,并返回数组中数据的平均值,我需要在这个程序中每个循环至少使用2个,并且不确定将它们放在何处。这个程序现在运行得很好,只需要为每个循环添加两个循环 这是我到目前为止所拥有的Java 如何在下面的代码中为每个循环添加2个?,java,arrays,foreach,Java,Arrays,Foreach,我需要写一个程序,把10个浮点数作为输入 程序应显示数字的平均值,后跟大于平均值的所有数字 我的部分需求包括编写一个方法,该方法将一个double数组作为参数,并返回数组中数据的平均值,我需要在这个程序中每个循环至少使用2个,并且不确定将它们放在何处。这个程序现在运行得很好,只需要为每个循环添加两个循环 这是我到目前为止所拥有的 public class Floats { public Floats() { } public static void main(Str
public class Floats {
public Floats() {
}
public static void main(String[] args) {
int count = 0, ct = 0, inc = 0, avc = 0, ac = 0, incre = 0, greaterCount = 0;
double sum = 0, average = 0, number = 0;
Scanner reader = new Scanner(System.in);
double[] array = new double[10];
double[] averageArray = new double[1];
double[] greaterArray = new double[10];
//inputs and appends to an array
while (count < array.length) {
System.out.print("Enter a number: ");
number = reader.nextInt();
array[count] = number;
sum = sum + number;
count++;
}
average = sum / count;
//counts
while (inc < array.length) {
if (array[inc] > average) {
greaterArray[inc] = array[inc];
incre++;
}
inc++;
}
//prints all numbers
System.out.println("All of the numbers entered: ");
while (avc < array.length) {
System.out.print(array[avc] + "," + " ");
avc++;
}
//average displayed
averageArray[0] = average;
System.out.println("");
System.out.println("The average of all numbers entered: ");
System.out.println(averageArray[0]);
//larger than average
System.out.println("Numbers greater than the average: ");
while (ac < inc) {
if (greaterArray[ac] != 0) {
System.out.println(greaterArray[ac]);
}
ac++;
}
}
}
提前谢谢你的帮助!如果你有任何问题,请告诉我 我不想为你做家庭作业,但我会尽力给你一个有用的建议。asListarray方法返回一个列表,该列表可以轻松用作for each循环的源 因为有人指出可以在实现Iterable的数组和集合上使用for-each循环,所以我上面的回答没有必要。考虑到这一点,我将提供一些示例代码:
String[] array = new String[] {"Test", "String", "Array"};
for (String string : array) {
}
打印双[]数组中的所有数字
打印数组中大于平均值的所有数字
看起来你想让我们帮你做作业,无论如何,我给你一个提示,for+ctrl+space。会有帮助吗?我刚刚注意到你根本没有for循环。。还有,为什么数组中的平均值只有一个元素?一行:put-forint i=0;iBut您也可以在一个数组上为每个执行一个。转换为列表是不必要的,这一点很好。我一直在实现Iterable的集合上使用for each循环,但忘记了它们使用数组。我还没有足够的声誉来评论DarkJade的答案,但这不是for each循环。祝贺你,你找到了答案。是的,我找到了答案,所以我给出了完整的答案
for (double d : array) {
System.out.print(d + ", ");
}
for (double d : array) {
if (d > average) {
System.out.println(d);
}
}