我正在创建一个简单的老虎机程序,问题是 else if
语句没有检查所有三个数字是否相同。我不太确定问题是什么,因为每当三个数字相同时,它只会打印“两个数字匹配”,而不是说“完美匹配”。
import java.util.Scanner;
import java.util.Random;
public class SlotMachine {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random random = new Random();
int slot1, slot2, slot3;
String choice;
System.out.println("Slot Machine Started!");
do{
slot1 = random.nextInt(2);
slot2 = random.nextInt(2);
slot3 = random.nextInt(2);
System.out.println(slot1+"||"+slot2+"||"+slot3);
//Two Matches
if(slot1 == slot2 || slot1==slot3||slot2==slot3) {
System.out.println("You got two matches!");
//All Matches
}else if (slot1==slot2 && slot2==slot3){
System.out.println("Perfect Match!! You win");
}else {
System.out.println("No matches, you suck!");
}
System.out.println("Would you like to spin again?");
choice = scan.nextLine();
}while(!choice.equalsIgnoreCase("No"));
System.out.println("Slot Machine Stopped!");
scan.close();
}
}
最佳答案
问题在于您组织条件的方式:每次出现三个数字匹配时,它也是一个两个数字匹配,因此您应该在前面进行更严格的检查限制较少的一个:
//All Matches
if(slot1==slot2 && slot2==slot3) {
System.out.println("Perfect Match!! You win");
}else if (slot1 == slot2 || slot1==slot3||slot2==slot3){
System.out.println("You got two matches!");
}else {
System.out.println("No matches, you suck!");
}
关于Java Else if 老虎机不检查所有数字是否相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28034545/