简体   繁体   中英

Count all values greater than 5.5 in an array java

I'm trying to print the count of numbers in the array that are greater than 5.5, but I have no idea where to start. I got the following code:

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);

    }

}

At the end it has to say: "Total numbers greater than 5.5: x"

Could anyone help me out?

Just iterate over the array and at each step check whether the current array element is greater than 5.5. If it is, increase a counter variable by 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);
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);

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM