首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在老虎机中只产生一个答案而不弹出另一个答案?

如何在老虎机中只产生一个答案而不弹出另一个答案?
EN

Stack Overflow用户
提问于 2019-04-16 05:33:36
回答 1查看 36关注 0票数 0

这里是java的初学者,所以对我手下留情吧,哈哈。我正在创建一个简单的3号老虎机,首先提示用户,如果他们想玩。用户输入一个正数进行播放,然后显示分配给一个槽号的3个随机数。如果用户匹配2个数字,则会显示“匹配2!”如果用户匹配所有三个,它就会说“大奖!”我现在的问题是,当用户获得大奖时,它仍然会说“匹配2!”就在“大奖!”下面!当用户获得大奖时,我如何才能让它甚至不检查匹配2,而继续循环?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-16 05:38:54

你需要改变你用来检查赢家的逻辑。您需要使用if-else语句,而不是使用多个if语句。主要区别在于if-else语句只允许执行第一个true语句,而跳过其余语句。

代码语言:javascript
复制
// 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!");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55697536

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档