从math.random改变有利的随机整数

时间:2014-01-17 04:17:59

标签: java android

我有以下代码:

public void onFinish() {
              int num;
              String outCome = "";
              for (int ii = 0; ii < 10; ii++) {
                  num = (int) (Math.random() * 100) % 3;

                  switch (num) {
                  case 0:
                      outCome = "ountcome1";
                      break;
                  case 1:
                      outCome = "outcome2";
                      break;
                  case 2:
                      outCome = "outcome3";
                      break;
             }
                text.setText(outCome);

我想要完成的是案例0有50%的机会发生,而案例1和2有25%的机会。

提前致谢!

3 个答案:

答案 0 :(得分:0)

使用:Random.nextInt(4),在情况0,3中返回“ountcome1” 在案例1中返回“ountcome2”并在案例2中返回“ountcome3”:

            switch (num) {
              case 0:
              case 3:
                  outCome = "outcome1";
                  break;
              case 1:
                  outCome = "outcome2";
                  break;
              case 2:
                  outCome = "outcome3";
                  break;
              ...          

答案 1 :(得分:-1)

使用此:

  for (int ii = 0; ii < 10; ii++) {
              num = (int) (Math.random() * 100) % 4; //Use 4 instead of 3

              switch (num) {
              case 0:
                  outCome = "ountcome1";
                  break;
              case 1:
                  outCome = "outcome2";
                  break;
              case 2:
                  outCome = "outcome3";
                  break;
              case 3:
                  outCome = "ountcome1";
                  break;

         }

因此,这里有四种可能的结果。如果获得0或3,则输出ountcome1(50%概率),否则输出另外两个。

答案 2 :(得分:-1)

尝试使用此

public void onFinish() {
          int num;
          String outCome = "";
          for (int ii = 0; ii < 10; ii++) {


              Random x = new Random(Calendar.getInstance().getTimeInMilliSec());
              num = x.nextInt(4);
              switch (num) {
              case 0:
                  outCome = "ountcome1";
                  break;
              case 1:
                  outCome = "outcome2";
                  break;
              case 2:
                  outCome = "outcome3";
                  break;
              case 3:
                  outCome = "ountcome1";
                  break;
         }
            text.setText(outCome);