java - RandomGenerator - 失去 50% 的平面模拟

标签 java

我正在处理一个我有点困惑的问题。问题是假设您是二战期间英国空军的一名将军。您还剩下 100 架飞机来保卫英国。在您执行的每个任务中,每架飞机都有 50% 的几率被德国高射炮击落,因此每次执行任务您都会损失大约一半的飞机。你必须编写一个程序来估计每次任务后有多少架飞机可以幸存下来,以及你可以运行多少架飞机直到所有飞机都被击落。

我的程序不工作,我不知道它出了什么问题,所以我猜英格兰有麻烦了。我试图用两个 while 循环来解决这个问题。外层的 while 循环表示只要你还有飞机,就派他们去执行另一个任务。内部 while 循环模拟实际任务。在 while 循环存在之后,飞机总数现在是幸存的飞机。

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();
      }

最佳答案

您必须在外循环中将 planeCounter 重置为 0。同样适用于 suvPlanes:

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

如果您不在此循环的第二次迭代中执行此操作,您将以 planeCounter >= planes 结束,因此您将不会执行内部循环。另一方面,suvPlanes 不会重置为 0,因此飞机在第一个循环中将永远保持等于 suvPlanes 的值,因此您的外循环将永远不会终止。

关于java - RandomGenerator - 失去 50% 的平面模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17336271/

相关文章:

java - 在 Android 中运行 USSD 代码并将 App 保持在第一位

java - 我们如何确保在不可变对象(immutable对象)中定义的 ArrayList 的不可变性?

java - 线程 “main”中的异常java.lang.IllegalStateException : The driver executable is a directory

java - 吉德DockableFrame : how do use WindowListener for my docking frame?

java - 如何将动态列数据导出到excel

java - 访问从另一个 jar 调用的方法

java - Java 中的 OutputStream 是阻塞的吗? ( socket )

java - 使用 web3j 库监听智能合约发出的事件

Java - 安排每日任务

java - NumberPicker 不适用于键盘