mercredi 24 décembre 2014

Working with random integers

Here is the assignment: For this program, there are two "parts". The first part will run the trials and determine how many caps each trial opens before finding a winning cap. Every trial (person) will be a winner. The number of caps opened by each trial is written to the file. (The output file should contain only integers). (This is where you will use nested loops...a for and a while...not two for's)


The second part of the program will read in the values and calculate the average. The average should be between 4.5 and 5.5 since there is a 1 in 5 chance of winning.


I know I have many mistakes, I want someone to tell me where to start. I do not know much about java.


My code:



int randNum = 0;
Random randNumList = new Random();

int counter = 0;
Scanner in = new Scanner(System.in);
System.out.println("How many trials will there be?");
int trials = in.nextInt();

int winner = 0;

PrintWriter outFile = new PrintWriter (new File("cap.txt"));
//run trials
for (int loop = 1; loop <= trials; loop++)
{
//select random number until 5 is selected
randNum = randNumList.nextInt(6);
for (randNum = randNumList.nextInt(6); randNum == 5; randNum++)
{
randNum = randNumList.nextInt(6);
counter++;
}

outFile.println(loop + " " + randNum);
}


outFile.close ( ); //close the file when finished

String token = " ";
Scanner inFile = new Scanner(new File("cap.txt"));

while (inFile.hasNext())
{
token = inFile.next();
if(token.equals("5"))
winner++;
}

double average = winner/counter;
System.out.println("The average number is " + average);




Aucun commentaire:

Enregistrer un commentaire