当我调用一个函数时,我的java循环很早就结束了,但当该函数未被调用时,它会正常工作
我在这里感到困惑。我正在写一个模拟掷骰子的程序。我有一个嵌套的for循环,其中包括一个计算值的函数调用。当我注释掉函数调用时,我的循环会迭代正确的次数。但是,当我包含函数调用时,循环总是提前终止。有人能帮我解释一下为什么会这样吗当我调用一个函数时,我的java循环很早就结束了,但当该函数未被调用时,它会正常工作,java,Java,我在这里感到困惑。我正在写一个模拟掷骰子的程序。我有一个嵌套的for循环,其中包括一个计算值的函数调用。当我注释掉函数调用时,我的循环会迭代正确的次数。但是,当我包含函数调用时,循环总是提前终止。有人能帮我解释一下为什么会这样吗 public class RollDice { /** Simulates the rolling of pair of dice * * @param num is an int between 2 and 12 inclusive
public class RollDice {
/** Simulates the rolling of pair of dice
*
* @param num is an int between 2 and 12 inclusive
* @return is the number of rolls it took to roll the value of num
*/
static int roll(int num) {
if (num <1 || num > 12) { // illegal value passed
throw new IllegalArgumentException("parameter must be between 1 and 12 inclusive");
}
int x, y; // integers between 1 and 6 inclusive
int count = 0; // number of times dice were rolled
/* roll dice once */
x = ( int)(6 * Math.random());
y = ( int)(6 * Math.random());
while (x + y != num) { // keep rolling dice until they equal num
count++;
/* roll dice again */
x = ( int)(6 * Math.random());
y = ( int)(6 * Math.random());
}
return count;
}
public static void main(String[] args) {
/* output a header */
System.out.printf("%10s %40s", "Total on Dice", "Average Number of Rolls\n");
System.out.println("---------------------------------------------------------");
for (int num = 2; num <= 12; num++) {
int total = 0;
for (int i = 0; i <= 10000; i++) {
total += roll(num); // num goes up to 10 when function is called instead of 12
} // end inner loop
System.out.println("num = " + num);
} // end outer loop
} // end main()
} // end class RollDice
公共类RollDice{
/**模拟一对骰子的滚动
*
*@param num是介于2和12之间的整数(包括2和12)
*@return是滚动num值所需的滚动次数
*/
静态整数滚动(整数){
如果(num 12){//传递了非法值
抛出新的IllegalArgumentException(“参数必须介于1和12之间,包括1和12”);
}
int x,y;//介于1和6之间(含1和6)的整数
int count=0;//掷骰子的次数
/*掷骰子一次*/
x=(int)(6*Math.random());
y=(int)(6*Math.random());
而(x+y!=num){//继续掷骰子,直到它们等于num为止
计数++;
/*再次掷骰子*/
x=(int)(6*Math.random());
y=(int)(6*Math.random());
}
返回计数;
}
公共静态void main(字符串[]args){
/*输出标题*/
System.out.printf(“%10s%40s”,“骰子总数”,“平均卷数\n”);
System.out.println(“------------------------------------------------------------------”;
对于(int num=2;num代码没有提前终止循环,当num为11时,它实际上永远不会从函数返回。因此,您的应用程序实际上处于无限循环中,并且永远不会完成
这是因为您正在生成从0到5(包括)的随机数。因此它们的总和永远不会达到11,函数也永远不会退出。将1添加到卷中,您将发现它现在退出。
( int)(6 * Math.random())
是从0到5的随机数。当num
达到11时,程序停止显示任何结果的原因是x+y
永远不会大于10
如果你有
(int) (1 + 6 * Math.random())
它会给你一个从1到6的随机数,我想这就是你想要的