我正在编写一个基本的老虎机代码,并且在程序运行时似乎陷入了无限循环。如果有人可以弄清楚该错误的出处或建议的方法。感谢所有帮助。
public class Java_Lab_3 {
public static void main(String[] args) {
int endgame;
int slot1;
int slot2;
int slot3;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in);
System.out.println("Want to test your luck?");
System.out.println("To Spin, type any positive number");
System.out.println("To End Game, type -1 and press enter ");
endgame = keyboard.nextInt();
while (endgame != -1) {
slot1 = rand.nextInt(10);
slot2 = rand.nextInt(10);
slot3 = rand.nextInt(10);
System.out.println(slot1 + slot2 + slot3);
System.out.println(endgame);
if (slot1 == slot2 && slot1 == slot3) { // Then they have JACKPOT
System.out.println("You've Won!");
} else if (slot1 == slot2 || slot2 == slot3 || slot1 == slot3) { // They MATCHED 2
System.out.println("We have twins... You've matched a pair!");
} else {
System.out.println("Sucks to Suck, don't quit your day job!");
}
}
}
}
答案 0 :(得分:0)
如果您想退出该循环,则必须对退出条件的可能性进行编程。例如...
while (endgame != -1) {
System.out.print("Do you want to play again? (-1 to quit): ");
endgame = keyboard.nextInt();
}
通过这种方式,您提示用户每次滚动后再次播放。
答案 1 :(得分:0)
您应该将endgame = keyboard.nextInt();
放到里面。并为其分配一些值(出于安全性考虑)
编辑:添加计数器功能
int endgame = 1;
int count1 = 0;
while (endgame != -1) {
endgame = keyboard.nextInt();
slot1 = rand.nextInt(10);
slot2 = rand.nextInt(10);
slot3 = rand.nextInt(10);
System.out.println(slot1 + slot2 + slot3);
count1++;
System.out.println(count1); //replace here
if (slot1 == slot2 && slot1 == slot3) { // Then they have JACKPOT
System.out.println("You've Won!");
} else if (slot1 == slot2 || slot2 == slot3 || slot1 == slot3) { // They MATCHED 2
System.out.println("We have twins... You've matched a pair!");
} else {
System.out.println("Sucks to Suck, don't quit your day job!");
}
}
答案 2 :(得分:0)
修改后的代码,在while循环内移动了用户提示:
public class Java_Lab_3 {
public static void main(String[] args) {
int endgame = 0;
int slot1;
int slot2;
int slot3;
Random rand = new Random();
Scanner keyboard = new Scanner(System.in);
while (endgame != -1) {
System.out.println("Want to test your luck?");
System.out.println("To Spin, type any positive number");
System.out.println("To End Game, type -1 and press enter ");
endgame = keyboard.nextInt();
slot1 = rand.nextInt(10);
slot2 = rand.nextInt(10);
slot3 = rand.nextInt(10);
System.out.println(slot1 + slot2 + slot3);
System.out.println(endgame);
if (slot1 == slot2 && slot1 == slot3) { // Then they have JACKPOT
System.out.println("You've Won!");
} else if (slot1 == slot2 || slot2 == slot3 || slot1 == slot3) { // They MATCHED 2
System.out.println("We have twins... You've matched a pair!");
} else {
System.out.println("Sucks to Suck, don't quit your day job!");
}
}
}
}