Java Else如果老虎机没有检查所有数字是否相同

时间:2015-01-19 22:24:06

标签: java if-statement

我正在创建一个简单的老虎机程序,问题是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();
}

 }

2 个答案:

答案 0 :(得分:4)

问题在于您组织条件的方式:每次有三位数匹配时,它也是一个两位数匹配,因此您应该将更严格的检查提前< /限制较少的一个:

//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!");
}

答案 1 :(得分:1)

如果您能用简单的语言阅读代码路径,则更容易发现。您只需要切换第一个和第二个条件来解决此问题。

I have numbers a,b,c

if a = b or a = c or b = c // This is also true in the case of all matches, so the code will stop executing this conditional here
    //I have two matches
else if a = b and b = c
    //I have all matches
else
    //have no matches