【问题标题】:How to add 2 For-Each Loops to the below code?如何在下面的代码中添加 2 个 For-Each 循环?
【发布时间】:2016-03-08 22:25:12
【问题描述】:

我需要编写一个以 10 个浮点数作为输入的程序。

程序应显示数字的平均值,然后显示所有大于平均值的数字。

我的部分要求包括编写一个将双精度数组作为参数并返回数组中数据的平均值的方法,并且我需要在此程序中使用至少 2 个 for-each 循环,并且我不知道把它们放在哪里。该程序现在可以完美运行,只需为每个添加的循环添加两个即可。

这是我目前所拥有的。

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++;
        }
    }
}

提前感谢您的帮助!如果您有任何问题,请告诉我!

【问题讨论】:

  • 这个好像是想让我们帮你做功课,反正我给你个提示,for+ctrl+space。
  • 会reading some documentation 帮忙吗?
  • 我刚刚注意到您根本没有 for 循环。另外,为什么数组中只有一个元素的平均值?
  • 一个衬垫:把 for(int i=0;i

标签: java arrays foreach


【解决方案1】:

我不想为你做作业,但我会尽力提供有用的建议。 Arrays.asList(array) 方法返回一个可以轻松用作 for-each 循环源的列表。

既然有人指出可以在数组和实现 Iterable 的集合上使用 for-each 循环,我上面的回答就没有必要了。考虑到这一点,我将提供一些示例代码:

String[] array = new String[] {"Test", "String", "Array"};
for (String string : array) {

}

【讨论】:

  • 但您也可以对数组执行 for-each。无需转换为列表。
  • 好点。我一直在实现 Iterable 的集合上使用 for-each 循环,却忘记了它们是数组。
  • 我还没有足够的声誉来评论 DarkJade 的回答,但这不是一个 for-each 循环。
【解决方案2】:

打印double[] array 中的所有数字。

for (double d : array) {
    System.out.print(d + ", ");
}

打印array中大于average的所有数字

for (double d : array) {
    if (d > average) {
        System.out.println(d);
    }
}

【讨论】:

  • 恭喜,你想通了。
  • 是的,我想通了,所以我给出了完整的答案
猜你喜欢
  • 2014-07-19
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 2012-09-20
相关资源
最近更新 更多