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 are the Situations in Which You Choose HashSet or TreeSet in ...

How Will You Sort Objects by Natural Order in a Java List ?

What are the Lifecycle Methods of a JSP ?

What are the Differences Between Collection and Collections in Ja ...

What is the Difference Between Queue and Stack Data Structures in ...