在数组java中计算大于5.5的所有值

时间:2016-10-03 11:23:27

标签: java arrays

我正在尝试打印数组中大于5.5的数字计数,但我不知道从哪里开始。我得到了以下代码:

package les5;

import java.util.*;

public class Les5 {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        System.out.print("How many numbers would you like to add? ");

        int totalNumbers = s.nextInt();
        double[] number = new double[totalNumbers];

        for (int i = 1; i <= totalNumbers; i++) {
            System.out.print("Number 1 " + i + ": ");
            number[i - 1] = s.nextDouble();
        }

        int numbCount = number.length;
        double avgNumber = Arrays.stream(number).sum() / number.length;


        System.out.println("Numbers count: " + numbCount);
        System.out.println("Average: " + avgNumber);

    }

}

最后它必须说:“总数大于5.5:x”

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:2)

迭代数组并在每一步检查当前数组元素是否大于5.5。如果是,则将计数器变量增加1.

double[] number = {10, 2, 3, 5, 6, 5.6};
int count = 0;
for (int i = 0; i < number.length; i++) {
    if (number[i] > 5.5) {
        count++;    
    }
}
System.out.println("Total numbers greater than 5.5: " + count);

答案 1 :(得分:0)

public class Les5 {

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    System.out.print("How many numbers would you like to add? ");

    int N = s.nextInt();
    double[] number = new double[N];
    // 
    int greaterThan5 = 0;
    for (int i = 0; i <= totalNumbers; i++) {
        System.out.print("Number " + i + ": ");
        number[i] = s.nextDouble();
        if(number[i] >5.5)
          greaterThan5++;
    }

    int numbCount = number.length;
    double avgNumber = Arrays.stream(number).sum() / number.length;


    System.out.println("Numbers count: " + numbCount);
    System.out.println("Average: " + avgNumber);

    System.out.println("Greater than 5: " + greaterThan5);

}

}