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

How Can We Analyze the Dependencies in Java Classes and Packages ...

What is the Difference Between remove Methods of Collection and I ...

What is a WeakHashMap in Java ?

What is the Use of Interceptor Design Pattern in Java ?

What are the Different Types of Classloaders in Java ?