Java Dice game won't work. need some advice
我的代码有问题,这是一个简单的骰子游戏:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.Random; class Zaruri { public static void main(String args[]) { Random roll = new Random(); int[] zar = new int[2]; for (int i = 0; i < 1; i++) { for(int k = 0; k < 2; k++){ zar[i] = (int) (roll* 6) + 1; } if (zar[0] == zar[1]) { System.out.println("Your numbers are :" + zar[0] +" and" + zar[1] +" You won! YEEEY!!"); } else { System.out.println("Your numbers are :" + zar[0] +" and" + zar[1] +" You lost, better luck next time!"); } } } } |
我不知道如何使它工作,首先它不会让第二个骰子打印出来(它总是0),如果我放了更多的1卷和(roll.nextDouble * 6)+ 1; 它会工作,但我不想要超过1卷。
你能帮助我吗 ? 我究竟做错了什么??
您不需要2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | for (int k = 0; k < 2; k++) { zar[k] = roll.nextInt(6) + 1; // k loop populates your array. } if (zar[0] == zar[1]) { System.out.println("Your numbers are :" + zar[0] +" and" + zar[1] +" You won! YEEEY!!"); } else { System.out.println("Your numbers are :" + zar[0] +" and" + zar[1] +" You lost, better luck next time!"); } |
有很多问题,我将逐一介绍它们
1 2 3 4 5 | for (int i = 0; i < 1; i++) { for(int k = 0; k < 2; k++){ zar[i] = (int) (roll* 6) + 1; } <snip rest of loop> |
带有k in的循环什么都不做,但多次重复
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | for (int i = 0; i < 1; i++) { for(int k = 0; k < 2; k++){ zar[i] = (int) (roll* 6) + 1; } if (zar[0] == zar[1]) { System.out.println("Your numbers are :" + zar[0] +" and" + zar[1] +" You won! YEEEY!!"); } else { System.out.println("Your numbers are :" + zar[0] +" and" + zar[1] +" You lost, better luck next time!"); } } |
print语句在for循环中,因此每次循环打印出来,第一次循环只会设置第一个die,第二次只有前两个等等。
1 | zar[i] = (int) (roll* 6) + 1; |
roll是随机类,它不是数字而是生成随机数,这应该是
1 | zar[i] = (int) (roll.nextDouble()* 6) + 1; |
或者更明智(因为你最终想要一个int
1 | zar[i] = roll.nextInt()+ 1; |
1 | for (int i = 0; i < 1; i++) |
从i = 0到i <1的数字只是一个数字0,骰子1从未被设置,因为它只经过一次循环
使用
然后它将无法在逻辑上工作并始终打印
您必须执行
试试这个:
1 2 3 | int Low = 10; int High = 100; int R = r.nextInt(High-Low) + Low; |
消息来源:如何在Android中生成特定范围内的随机数?
或Java在两个给定值之间生成随机数
我不明白为什么你有两个循环,特别是那个以
1 2 3 | for (int i = 0; i < 2; i++) { zar[i] = roll.nextInt(6) + 1; } |
尝试使用Math.random()而不是Random()