这里是java的初学者,所以对我手下留情吧,哈哈。我正在创建一个简单的3号老虎机,首先提示用户,如果他们想玩。用户输入一个正数进行播放,然后显示分配给一个槽号的3个随机数。如果用户匹配2个数字,则会显示“匹配2!”如果用户匹配所有三个,它就会说“大奖!”我现在的问题是,当用户获得大奖时,它仍然会说“匹配2!”就在“大奖!”下面!当用户获得大奖时,我如何才能让它甚至不检查匹配2,而继续循环?
import java.util.Random;
import java.util.Scanner;
public class SlotMachine{
public static void main(String []args){
Random rnd = new Random();
Scanner key = new Scanner(System.in);
int slot1;
int slot2;
int slot3;
int play;
String input;
//end of variables
System.out.println("Play the simple slot machine. To continue \nplaying enter ANY positive number. To stop \nplaying enter a negative 1.");
System.out.println("Wanna play? :");
input = key.nextLine();
play = Integer.parseInt(input);
while (play > 0) {
slot1 = rnd.nextInt(3);
slot2 = rnd.nextInt(3);
slot3 = rnd.nextInt(3);
System.out.println("Slot 1: " + slot1 + "\tSlot 2: " + slot2 + "\tSlot 3: " + slot3);
if (slot1 == slot2 && slot2 == slot3) {
System.out.println("Jackpot!");
}//Checking to see if all 3 slots match and returning a Jackpot!
if (slot1 == slot2 || slot2 == slot3 || slot1 == slot3) {
System.out.println("Matched 2!");
}//Checking to see if any 2 slots match
System.out.println("Wanna play?");
input = key.nextLine();
play = Integer.parseInt(input);
if (play == -1) {
System.out.println("Thanks for playing!");
}//end if -1
}
}//end main
}//end class
发布于 2019-04-16 05:38:54
你需要改变你用来检查赢家的逻辑。您需要使用if-else语句,而不是使用多个if语句。主要区别在于if-else语句只允许执行第一个true语句,而跳过其余语句。
// check if all three numbers match, if this is true the else-if is skipped
if (slot1 == slot2 && slot2 == slot3) {
System.out.println("Jackpot!");
// check if two numbers match
} else if (slot1 == slot2 || slot2 == slot3 || slot1 == slot3) {
System.out.println("Matched 2!");
}
https://stackoverflow.com/questions/55697536
复制相似问题