dimanche 11 septembre 2016

How do I get the correct sum of a series of random numbers in a 'for loop'

I'm creating a program that creates a 10 play football drive. I have three Random objects. One pulls random players and plays. The second pulls random numbers for positive gains and the third pulls random numbers for a negative play when the quarterback is sacked.

The problem I have is I want to be able to calculate the total yards of the drive after the loop concludes (positive yards - negative yards) and I can't get the numbers to add up correctly. Any ideas?

public void callPlays() {

Random random = new Random();       //plays and players
Random yardsGained = new Random();  //positive plays
Random yardsLost = new Random();    //negative plays

int totalYards=0;
int numberOfYards = 0;
int lossOfYards = 0;

System.out.println("Redskins begin drive on their own 20 yard line");

for(int i=0;i<10;i++) 
{

    numberOfYards = yardsGained.nextInt(16);
    lossOfYards = yardsLost.nextInt(16);


    String[] passCatchers = new String[6];

    passCatchers[0] = "DeSean Jackson";
    passCatchers[1] = "Pierre Garcon";
    passCatchers[2] = "Jamison Crowder";
    passCatchers[3] = "Jordan Reed";
    passCatchers[4] = "Matt Jones";
    passCatchers[5] = "Chris Thompson";

    int passCatcher = random.nextInt(passCatchers.length); 

    String[] backs = {"Matt Jones", "Chris Thompson"};

    int runningBack = random.nextInt(backs.length);

    String[] plays = new String[7];

    plays[0] = "Pass complete to " + passCatchers[passCatcher]  
    + " for " + numberOfYards + " yards.";

    plays[1] = "Handoff to " + backs[runningBack] + " along the left   
    edge for " + numberOfYards + " yards.";

    plays[2] = "Handoff to " + backs[runningBack] + " up the middle for 
    " + numberOfYards + " yards.";

    plays[3] = "Handoff to " + backs[runningBack] + " along the right  
    edge for " + numberOfYards + " yards.";

    plays[4] = "Screen pass to " + passCatchers[passCatcher] + " for "  
    + numberOfYards + " yards";

    plays[5] = "Kirk Cousins scrambles for " + numberOfYards + " 
    yards";

    plays[6] = "Kirk Cousins sacked for " + lossOfYards + " yards.";

    int select = random.nextInt(plays.length); 
    System.out.println(plays[select]);


}

totalYards = numberOfYards - lossOfYards;  //does not add up correctly
System.out.println("10 play drive. " + totalYards + " yards.")




Aucun commentaire:

Enregistrer un commentaire