0

好的,对于大学来说,我们必须创建两个 Die 对象并滚动它们几次,计算出现的蛇眼的数量。

这是我拥有的代码,我需要一些帮助,因为每次编译和执行我的程序时,我都会失败。我不能 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 回答