Maya - 1 year ago 91
Java Question

# How to make a loop repeat another loop?

The code below gives you a number close to pi when you run the program. It takes the user input for the number of darts you want thrown per trial, and uses that to come up with the number close to pi. I need to make the code run for a specific number of trials, but can't seem to make it work. How do I do this?

``````    System.out.print("How many darts per trial? ");
int darts = in.nextInt();
System.out.print("How many trials? ");
int trials = in.nextInt();

//The code below this represents 1 trial
for(int i = 0; i < darts; i++)
{
xInt[i] = (Math.random() * (upper - lower)) + lower;
yInt[i] = (Math.random() * (upper - lower)) + lower;
c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2);
c[i] = Math.sqrt(c2[i]);

if(c[i] <= 1)
{
hits++;
}
}
double answer = 4 * ((double)hits / (double)darts);
``````

If I added the for-loop for the trials (see below), then it adds up all of the answers and prints the sum

``````for(int n = 0; n < trials; n++)
{
for(int i = 0; i < darts; i++)
{
xInt[i] = (Math.random() * (upper - lower)) + lower;
yInt[i] = (Math.random() * (upper - lower)) + lower;
c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2);
c[i] = Math.sqrt(c2[i]);
if(c[i] <= 1)
hits++;
}
}

double answer = 4 * ((double)hits / (double)darts);
``````

It should print out something like this when you are finished.

``````Trial [1]: pi = 3.11341744
Trial [2]: pi = 3.04824237
Trial [3]: pi = 3.33281081
Trial [4]: pi = 3.40901039
``````

You need to reset the number of hits for each trial by adding a hits=0; right after the trials for loop Furthermore move your calculation and print statement inside the for loop. Like this:

``````for(int n = 0; n < trials; n++)
{
hits=0;
for(int i = 0; i < darts; i++)
{
xInt[i] = (Math.random() * (upper - lower)) + lower;
yInt[i] = (Math.random() * (upper - lower)) + lower;
c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2);
c[i] = Math.sqrt(c2[i]);
if(c[i] <= 1)
hits++;
}
double answer = 4 * ((double)hits / (double)darts);