我正在制作一个简单的乐透游戏,但是当我输入一些数字并将骰子设置为只有1(100%获胜的机会)时,我仍然会得到失败的结果。 另外,如何才能将坏运气声明仅打印一次?我知道你可以制作一个布尔值,但有更简单的方法吗?
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num = 0;
int randnum = 0;
Random gen = new Random();
Scanner scan = new Scanner(System.in);
System.out.println("Enter desired numbers to be drawn");
int print = scan.nextInt();
System.out.println("Enter desired numbers on dice");
int dice = scan.nextInt();
System.out.println("Enter your lucky numbers");
int[] numbers = new int[print];
for(int i=0; i<print;i++){
numbers[i] = scan.nextInt();
}
for(int counter=1; counter<=print;counter++){
randnum = 1+gen.nextInt(dice);
System.out.println(randnum + " ");
System.out.println();
if (randnum == num){
System.out.println("Winner winner chicken dinner!");
} else
System.out.println("Bad luck!");
}
}
}
答案 0 :(得分:1)
问题很简单。你没有将randnum与正确的变量进行比较。你要做的是通过以下方式替换你的病情:
if (randnum == numbers[counter - 1]){
System.out.println("Winner winner chicken dinner!");
} else
System.out.println("Bad luck!");
}
答案 1 :(得分:1)
这是因为,num总是0(它没有改变),并且因为你调用randnum = 1 + gen.nextInt(骰子),randnum总是&gt; = 1;
我想,你需要在第22行添加:
num = numbers[counter-1];
它应该是:
package findarray2;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num = 0;
int randnum = 0;
Random gen = new Random();
Scanner scan = new Scanner(System.in);
System.out.println("Enter desired numbers to be drawn");
int print = scan.nextInt();
System.out.println("Enter desired numbers on dice");
int dice = scan.nextInt();
System.out.println("Enter your lucky numbers");
int[] numbers = new int[print];
for(int i=0; i<print;i++){
numbers[i] = scan.nextInt();
}
for(int counter=1; counter<=print;counter++){
num = numbers[counter-1];
randnum = 1+gen.nextInt(dice);
System.out.println(randnum + " ");
System.out.println();
if (randnum == num){
System.out.println("Winner winner chicken dinner!");
} else
System.out.println("Bad luck!");
}
}
}
答案 2 :(得分:0)
你永远不会改变num的值。它始终为0.根据我的理解,您想要的是检查您输入的数字是否相同且外观顺序相同,因此您需要检查if (randnum == numbers[counter-1])
如果您只想打印一次字符串"Bad luck!"
,最好的方法是使用boolean
。还有另一种可怕的方法,即使用break;
,但如果您这样做,世界将会结束。您可以做的另一件事是设置counter = print+1
,这与使用break
实际上相同