gpt4 book ai didi

java - 为什么这个 while 循环在 roll and roll 2 之后不停止?

转载 作者:行者123 更新时间:2023-11-29 03:05:51 26 4
gpt4 key购买 nike

我创建了一个简单的掷骰子程序。但是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 );


}
}

最佳答案

因为在 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 循环 roll1roll2 有一个随机值,但是如果你不使用我添加的新行更改这个值,那么您将始终循环到您拥有的相同值。

关于 roll1 和 roll2 值的变化,这对我来说没有意义,在我的电脑上你的代码结果是:

启动 1

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

启动 2

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

关于java - 为什么这个 while 循环在 roll and roll 2 之后不停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32225897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com