为什么这个while循环在roll1和roll2之后停止?

时间:2015-08-26 11:51:37

标签: java random while-loop

我创建了一个简单的骰子滚动程序。但是while循环不会停止 roll1和roll2相等。而总数并没有增加。程序运行无限次,我必须停止它。请帮忙。

输出:

Roll #1: 1
Roll #2: 2
Total is : 3
Roll #1: 4
Roll #2: 1
Total is : 3
Roll #1: 4
Roll #2: 4
Total is : 3
Roll #1: 2
Roll #2: 5
Total is : 3
Roll #1: 4
Roll #2: 4
Total is : 3
Roll #1: 0
Roll #2: 2
Total is : 3
Roll #1: 4
Roll #2: 3
Total is : 3

源代码:

import java.util.Scanner;
import java.util.Random;

public class App1
{
    public static void main( String[] args )
    {
        Random r = new Random();

        int roll1 = 1+ r.nextInt(6);
        int roll2 = 1+ r.nextInt(6);
        int total = roll1 + roll2;

        System.out.println("Heres comes the dice!");
        System.out.println();


        while ( roll1 != roll2 )
        {
            System.out.println("Roll #1: "  + roll1);
            System.out.println("Roll #2: "  + roll2);
            System.out.println("Total is : " + total );

        }
        System.out.println("Roll #1: "  + roll1);
        System.out.println("Roll #2: "  + roll2);
        System.out.println("Total is : " + total );


    }
 }

2 个答案:

答案 0 :(得分:3)

因为在while while循环中你不会获得新值:

while ( roll1 != roll2 )
{
    System.out.println("Roll #1: "  + roll1);
    System.out.println("Roll #2: "  + roll2);
    System.out.println("Total is : " + total );

    roll1 = 1+ r.nextInt(6);
    roll2 = 1+ r.nextInt(6);
    total = roll1 + roll2;
}

首次输入while循环roll1并且roll2具有随机值,但如果您不使用我添加的新行更改此值,那么您将始终循环用你所拥有的相同价值观。

关于roll1和roll2更改的值,对我来说没有意义,在我的计算机中,您的代码结果是:

<强> Launch1

Total is : 7
Roll #1: 1
Roll #2: 6
Total is : 7
Roll #1: 1
Roll #2: 6
Total is : 7
Roll #1: 1
Roll #2: 6
Total is : 7

<强> Launch2

Total is : 8
Roll #1: 5
Roll #2: 3
Total is : 8
Roll #1: 5
Roll #2: 3
Total is : 8
Roll #1: 5
Roll #2: 3
Total is : 8

答案 1 :(得分:1)

你想滚动直到骰子滚动相同,这意味着:

  1. 需要在循环中 创建随机值。否则,循环根本不会执行,或者循环是无限循环。
  2. 使用 do-while 循环可以获得更好的代码。
  3. Random r = new Random();
    
    System.out.println("Heres comes the dice!");
    System.out.println();
    int roll1, roll2;
    do
    {
        roll1 = 1+ r.nextInt(6);
        roll2 = 1+ r.nextInt(6);
        int total = roll1 + roll2;
        System.out.println("Roll #1: "  + roll1);
        System.out.println("Roll #2: "  + roll2);
        System.out.println("Total is : " + total );
    } while (roll1 != roll2);