【发布时间】:2014-01-12 22:01:26
【问题描述】:
在这方面是 Java 新手。我正在尝试运行一个掷两个骰子的程序,当两个骰子之间的总掷骰数为 7 或 11 时,程序将退出。出于某种原因,我的 while 语句一遍又一遍地执行,我不知道为什么。任何帮助将非常感激。代码如下。
再次,对此非常陌生。目前并不太关注一种更有效的方法来做到这一点,而是关注为什么它不起作用的语义细节。
// import required packages for the program
// import all classes to be on the safe side
// will be using input/ouput and math, so those imports are needed
import java.io.*;
import java.math.*;
import java.text.*;
// Declare a class, class name Dice chosen
public class Dice
{
// need to use throws IOException because we are dealing with input and output, simple main method will not suffice
public static void main(String[] args) throws IOException
{
// declare variables for the two dice, randomize each
// die can each be rolled for # between 1-6
double dice1 = Math.round(Math.random() * 6) + 1;
double dice2 = Math.round(Math.random() * 6) + 1;
// declare variable for combined roll
double totalRoll = dice1 + dice2;
//create loop to determine if totalRoll is a 7 or 11, if not continue rolling
while ((totalRoll != 7.0) || (totalRoll != 11.0))
{
dice1 = Math.round(Math.random() * 6) + 1;
dice2 = Math.round(Math.random() * 6) + 1;
totalRoll = dice1 + dice2;
System.out.println("The roll on die 1 is: " + dice1);
System.out.println("The roll on die 2 is: " + dice2);
System.out.println("The total of the two rolls is: " + totalRoll + "\n");
if ((totalRoll == 7.0) || (totalRoll == 11.0))
{
System.out.println("You win!");
}
}
/*
// declare in as a BufferedReader; used to gain input from the user
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
//Simulate tossing of two dice
*/
}
}
【问题讨论】:
-
(totalRoll != 7.0) || (totalRoll != 11.0)是什么意思?一个数字可以等于两个值吗? -
如果总点数不是 7 或 11,则重新掷骰子,直到命中 7 或 11
-
你为什么用
doubles来代表骰子?想想你希望他们能够拥有哪些价值观。 -
我知道它们是整数,但表示 .0 并不会真正影响程序功能,是吗?
-
@Zack,如果掷出 7,
while将仍然继续,因为它也不等于 11。totalRoll == 7.0而是totalRoll != 11.0。这满足条件,因为您使用的是OR。
标签: java while-loop