Sythe
Sythe

Reputation: 143

Take an iterable variable out of a for-loop

Having some difficulty taking an iterable variable used in a for-loop out in order to be used to find the average amount of returned values for 100 times the loop occurs. Some background: There is a 24m long tunnel needed to be mined by rolling a D6 each week. On a 6, the tunnel collapses and you must restart. For each value on the dice, you have mined that far (plus the previous week). How long will it take to clear the tunnel? I'm trying to find the average of this across 100 attempts.

import java.util.Random;

class avgD6{
  public static void main(String[] args){
    int sum = 0;
    for(int x = 0;x<101;x++){
      int progress = 0;
      for(int i = 0; i>=0;i++){
        Random rand = new Random();
        int d = rand.nextInt(6)+1; //roll of a six-sided die
        if(d==6){
          progress = 0; //progress resets, tunnel collapses
        }
        else{
          progress+=d;
        }
        if(progress>=24){
          //System.out.println("The weeks it took was: "+i);
          break;
        }
      }
      sum+=i;
    }
    double avg = sum/x;
    System.out.println(avg);
  }
}

Upvotes: 1

Views: 85

Answers (1)

rgettman
rgettman

Reputation: 178263

Declare the variables immediately before the for loop that iterates over them, so that their scope is larger and they can be seen when they're referenced later.

int x = 0;
for(x = 0;x<101;x++){

and

int i = 0;
for(i = 0; i>=0;i++){

Then the sum+=i; statement can see i, and the double avg = sum/x; can see x.

Additionally, be aware that the division of two ints in Java must be an int, so any decimal portion is truncated, e.g. 15/10 is 1, not 1.5. Cast one of the to double to force floating-point division.

double avg = (double) sum / x;

Upvotes: 1

Related Questions