Java How To Find The Average Of 10 Numbers Using A While Loop

Here's a Java example of how to find the average of 10 randomly generated numbers using a while loop:


import java.util.Random;

public class AverageCalculator {
    public static void main(String[] args) {
        int count = 0;     // Initialize count to 0
        double sum = 0.0;  // Initialize sum to 0.0
        Random random = new Random();

        // Use a while loop to generate and sum 10 random numbers
        while (count < 10) {
            double number = random.nextDouble() * 100; // Generate a random number between 0 and 100
            System.out.println("Generated random number: " + number);
            sum += number; // Add the random number to the sum
            count++;      // Increment the count
        }

        // Calculate the average
        double average = sum / 10;

        // Display the average
        System.out.println("The average of the 10 random numbers is: " + average);
    }
}

In this program, we're using a while loop to generate 10 random numbers between 0 and 100, calculate their average, and display the result. The Random class is used to generate random numbers, and the average is calculated in the same way as in the previous examples.



You May Interest

What is the Purpose of Spring Configuration File ?

Why Does Java Provide Default Constructor ?

How HashMap Works in Java ?

Replacing Hashtable With ConcurrentHashMap in Java

What is the Reason to Organize Classes and Interfaces in a Packag ...