Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RandomGenerator - Losing 50% of planes simulation

Tags:

java

I'm working on a problem that I'm a little confused on. The question says imagine you're a general of the British Air Force during WW2. You have 100 planes left to defend the United Kingdom. With each mission you fly each plane has a 50% chance of getting shot down by the German anti aircraft guns so every mission you'll lose about half of your planes. You have to write a program that will approximate how many planes will survive after each mission and how many missions you can run until all your planes get shot down.

My program does not work and I don't know what wrong with it so I guess England is in trouble. I'm trying to solve this problem with two while loops. The outer while loop says as long as you have planes left send them on another mission. The inner while loop simulates the actual mission. After the while loop exists the total number of planes is now the surviving planes.

import acm.program.*; 
import acm.util.*;

public class MissionPlanes extends ConsoleProgram{
public void run(){

  int planes = 100;  /* total number of planes */
  int suvPlanes = 0;  /* surviving planes  */
  int mission = 0;      /* total number of missions */
  int planeCounter = 0;   /* keeps track of the planes flying over the anti plane gun  */


  while (planes > 0){

       while(planeCounter < planes){
             planeCounter++;
             if(rgen.nextBoolean()){   /* I've tried rgen.nextBoolean() with paramaters and with no paramaters */
              suvPlanes += 1;
                   }
            }
    planes = suvPlanes;
    mission++;
 println("The total number of surviving planes you have is " + planes + "after" + missoin + "missions"); 
     }
  }
  private RandomGenerator rgen = RandomGenerator.getInstance();
      }
like image 340
Jessica M. Avatar asked Jun 27 '13 06:06

Jessica M.


1 Answers

You will have to reset planeCounter to 0 in the outer cycle. Same holds for suvPlanes:

while (planes > 0){
  planeCounter = 0;
  suvPlanes = 0;
  // ... remaining stuff

If you don't do that on the second iteration of this cycle you will end up with planeCounter >= planes so you will not execute the inner cycle. On the other hand suvPlanes will not be reset to 0 so planes will forever remain equal to the value of suvPlanes in the first cycle and thus your outer cycle will never terminate.

like image 121
Ivaylo Strandjev Avatar answered Sep 21 '22 01:09

Ivaylo Strandjev