使Math.Random循环直到达到特定数字

时间:2014-10-20 21:25:35

标签: java math random dice

我正试图制作一个“滚动两个骰子”的节目。并结合数量和需要继续前进,直到达到特定数字7或11,但每次运行它都会一直持续下去。

double total = 0;
while (total != 7 || total != 11) {
    DecimalFormat x = new DecimalFormat("#");
    double dice1 = Math.random() * 6 + 1;
    double dice2 = Math.random() * 6 + 1;
    double total = (dice1 + dice2);
    System.out.println("Dice 1: " + x.format(dice1) + " Dice 2: " + x.format(dice2) + " Total: " + x.format(total));

    }

我认为这是因为int total设置为0并且不能从循环中得到总数但是我该如何解决这个问题呢?

3 个答案:

答案 0 :(得分:5)

您的while循环逻辑不正确。总数不会是7或不是11。你需要“和”,而不是&&。变化

while (total != 7 || total != 11) {

while (total != 7 && total != 11) {

另外,我不知道任何产生非整数的骰子,所以我会将结果转换为int并声明dice1dice2和{{1} } total s。

答案 1 :(得分:4)

这是因为你影了total,你需要测试逻辑和(不是或)。我还希望使用RandomnextInt(int)之类的

int total = 0; // <-- don't shadow me.
Random rand = new Random(); 
while (total != 7 && total != 11) {
  int dice1 = rand.nextInt(6) + 1; // <-- using rand.
  int dice2 = rand.nextInt(6) + 1;
  total = (dice1 + dice2); // <-- no double.
  System.out.printf("Dice 1: %d Dice 2: %d Total: %d%n", dice1, dice2, total);
}

答案 2 :(得分:0)

您需要AND而不是OR。并尝试使用int:

int total = 0;
    while (total != 7 && total != 11) {
        Random rand = new Random();
        int dice1 =  rand.nextInt((6 - 1) + 1) + 1;
        int dice2 =  rand.nextInt((6 - 1) + 1) + 1;
        total = (dice1 + dice2);
        System.out.println("Dice 1: " + dice1 + " Dice 2: " +dice2 + " Total: " + total);
相关问题