0

大学では、Die オブジェクトを 2 つ作成し、それらを数回転がして、発生するスネークアイの数を数えます。

これは私が持っているコードです。プログラムをコンパイルして実行するたびに失敗するので、助けが必要です。どこが間違っているのか100%確信が持てません.私の大学に行かない限り、解決策が役立つかどうかは完全にはわかりません.

失敗は - http://i.imgur.com/ghcOlpP.png

(これはすべて JPLIDE でコーディングされています)

final int ROLLS = 500;
  int num1, num2, count = 0;

  Die die1 = new Die();
  Die die2 = new Die();

  for (int roll=1; roll <= ROLLS; roll++)
  {num1 = 1;
    num2 = 1;

    if (num1 == 1 && num2 == 1)    // check for snake eyes
      count++;
  }

  System.out.println ("Number of rolls: " + ROLLS);
  System.out.println ("Number of snake eyes: " + count);
  System.out.println ("Ratio: " + (float)count / ROLLS);
}}}

class Die
{private final int MAX = 6;  // maximum face value
  private int faceValue;  // current value showing on the die

  //-----------------------------------------------------------------
  //  Constructor: Sets the initial face value of this die.
  //-----------------------------------------------------------------
  public Die()
  {faceValue = 1;
  }

  //-----------------------------------------------------------------
  //  Computes a new face value for this die and returns the result.
  //-----------------------------------------------------------------
  public int roll()
  {faceValue = (int)(Math.random() * MAX) + 1;
    return faceValue;
  }

  //-----------------------------------------------------------------
  //  Face value mutator. The face value is not modified if the
  //  specified value is not valid.
  //-----------------------------------------------------------------
  public void setFaceValue (int value)
  {if (value > 0 && value <= MAX)
    faceValue = value;
  }

  //-----------------------------------------------------------------
  //  Face value accessor.
  //-----------------------------------------------------------------
  public int getFaceValue()
  {return faceValue;
  }

  //-----------------------------------------------------------------
  //  Returns a string representation of this die.
  //-----------------------------------------------------------------
  public String toString()
  {String result = Integer.toString(faceValue);
    return result;
  }
}
4

1 に答える 1

0
for (int roll=1; roll <= ROLLS; roll++) {
num1 = 1;
num2 = 1;

if (num1 == 1 && num2 == 1)    // check for snake eyes
  count++;
}

これは間違っているようです。設定num1 = 1してnum2 = 1から、両方が1に等しいかどうかを確認します..もちろん、それらは1に等しくなります。次のようなことをするつもりだったと思います

num1 = die1.roll() num2 = die2.roll()

これにより、少なくとも 500 回すべて蛇の目になることはありません。

于 2015-08-20T01:34:58.247 に答える