Reputation: 63
I'm a beginner Java student faced with the following question: W"rite a program that inputs an integer that will be the number of times (n) that you will read a random number."
The program is then supposed to calculate the sum and product of those random numbers.
I understand how to generate a random number and I set up a For loop to generate the n random numbers per user input.
import java.util.Scanner;
import java.util.Random;
public class Example {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter a number:");
n = input.nextInt();
for (int i = 0; i < n; i++){
double randomNumber = Math.random();
System.out.println(randomNumber);
}
}
}
My first attempt had shoehorned
System.out.println(randomNumber * randomNumber);
System.out.println(randomNumber + randomNumber);
at the bottom of the code which did not work for reasons that are probably obvious to anyone else.
I'm stuck on the concept of storing n random numbers for long enough to do the required arithmetic on them.
Upvotes: 0
Views: 915
Reputation: 521103
You should be able to just maintain some state for the sum and product:
int n = input.nextInt();
double sum = 0d;
double product = 0d;
for (int i=0; i < n; i++) {
double randomNumber = Math.random();
sum += randomNumber;
product = i == 0 ? randomNumber : product*randomNumber;
}
System.out.println("sum = " + sum);
System.out.println("product = " + product);
The line:
product = i == 0 ? randomNumber : product*randomNumber;
is equivalent to:
if (i == 0) {
product = randomNumber;
}
else {
product = product*randomNumber;
}
The version I used is called a ternary expression, and is a concise way of writing if else logic. The idea here is that we want to initialize the product with the first random number. Otherwise, we just multiply the product with the latest random number.
Upvotes: 1