2024_Programming_Training_D.../CS5 - Challenge Solution/Main.java

52 lines
1.9 KiB
Java

import java.util.Random;
import java.util.Scanner;
/*
CS5 Challenge Solution
Original Challenge Description: Write a program that requests an integer
from the user, and prints that many random numbers AND prints the sum
and average of those numbers.
*/
public class Main {
public static void main(String[] args) {
//Setup our random number generator and a scanner
//to get input from the user
Random random = new Random();
Scanner scan = new Scanner(System.in);
//Get the number of random numbers the user
//wants us to generate
System.out.print("Number of random values to create: ");
int numberToRandomize = scan.nextInt();
//Close the scanner, we shouldn't need it anymore.
scan.close();
//Create a variable to store the sum of all the numbers
//we're about to generate. Notice that it is a DOUBLE,
//not an int
double sum = 0;
//Setup a for loop, this loop will run for the number
//of random numbers the user requested.
for(int i = 0; i < numberToRandomize; i++) {
//Generate a random number and store it temporarily
double randomNumber = random.nextDouble();
//Properly print the current random number (i + 1),
//along with the number that we actually generated
System.out.println("Random Number " + (i + 1) + ": " + randomNumber);
//Add the current random number to the sum.
//sum += randomNumber is equivalent to sum = sum + randomNumber
sum += randomNumber;
}
//Print the sum, and then print the average.
//The average being the sum divided by the number of numbers
//to randomize requested by the user.
System.out.println("Sum = " + sum);
System.out.println("Average = " + (sum / numberToRandomize));
}
}