Java – randomgenerator – lost 50% of aircraft simulation
I'm working on a problem that I'm a little confused The problem is, suppose you were a general of the British air force during World War II You still have 100 planes to defend Britain Every mission, every aircraft has a 50% chance of being shot down by German anti-aircraft guns, so about half of the aircraft will be lost in each mission You have to write a program to estimate how many planes will survive each mission and how many missions you can run until all planes are shot down
My program doesn't work. I don't know what's wrong with it, so I guess England is in trouble I tried to solve this problem with two while loops The external while loop means that you can send them to another task as long as you have planes The internal while loop simulates the actual task 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(); }
Solution
You must reset planecounter to 0 in the outer loop So is suvplanes:
while (planes > 0){ planeCounter = 0; suvPlanes = 0; // ... remaining stuff
If you don't do this in the second iteration of this loop, you will eventually get planecounter > = plane, so you won't execute the inner loop On the other hand, suvplanes will not be reset to 0, so the plane will always remain equal to the value of suvplanes in the first cycle, so your external loop will never end