为什么我的 IF-ELSE-IF 语句不能正常工作?

huangapple go评论69阅读模式
英文:

Why won't my IF-ELSE-IF statement work correctly?

问题

我正试图在Java中创建一个简单的21点(Blackjack)游戏。我有一个带有可能选项为1-4的整数的菜单。如果用户输入的整数大于4,我的IF语句需要打印出"无效整数",然后重新开始游戏。如果用户输入负值,我的ELSE-IF语句需要做同样的事情。

然而,这些语句只会起作用一次,因此我不能让"无效整数"在我连续多次输入小于0和大于4的值时打印出来。

[已删除]

任何帮助将不胜感激。

英文:

I am trying to create a simple Blackjack game in Java. I have a menu with possible integer options from 1-4. If the user inputs an integer greater than 4, my IF statement needs to print "invalid integer" and then restart the game. If the user inputs a negative value, my ELSE-IF statement needs to do the same thing.

However, the statements will only work once, so I can't get "invalid integer" to print if I input values below 0 and values greater than 4 multiple times/back-to-back.

[Redacted]

Any help is appreciated.

答案1

得分: 1

如果您已经像这样定义了scnr

Scanner scnr = new Scanner(System.in);

我建议您使用一个带有默认子句的简单switch case语句。

switch (userOpt) {
    case 1:
        // 选项1的逻辑...
    case 2:
        // 选项2的逻辑...
    case 3:
        // 选项3的逻辑...
    case 4:
        // 选项4的逻辑...
    default:
        // 处理无效输入...
}
英文:

If you have defined scnr like this:

Scanner scnr = new Scanner(System.in);

I suggest you do a simple switch case statement with a default clause.

switch (userOpt) {
    case 1:
        // Option 1 logic...
    case 2:
        // Option 2 logic...
    case 3:
        // Option 3 logic...           
    case 4:
        // Option 4 logic...
    default:
        // Handling invalid input...
}

答案2

得分: 0

你写的代码真的很混乱
例如第一种情况下是如何获得另一张牌的
代码都写在一个主函数里吗你可以创建一个名为BlackJack的类其中包含getCard()holdHand()等不同的方法还可以设置一个类变量来保存手牌游戏局数以及庄家/玩家的胜利次数这样会更容易理解你的代码
然后你可以在代码内部的主函数中调用它就像这样

```python
class BlackJack:
    # 类变量,如手牌、玩家胜利次数等

    # 方法在这里定义

    # 主函数,用于测试你的代码

我希望你能理解我的建议,我知道在你已经编写好代码的情况下现在可能会感觉需要做很多工作,但这会帮助你和任何阅读你代码的人理解代码逻辑。


<details>
<summary>英文:</summary>

It&#39;s really confusing in the way you&#39;ve written the code. 
I.e how does case 1 involve get another card? 
Is all the code written in a main function? How about you make a class called blackjack in which you have different methods for getCard(), holdHand() etc. and make a class variable which holds the hand and also gamecount and wins for dealer/player. Would be much easier to understand your code. 
Then you can try you code in your main inside the code.

Something like;

    public BlackJack { 
    **class variables such as hand, player wins etc..**

    **methods here**
    
    **main method to try your code**
    }




I hope you get what I&#39;m suggesting, I know it might feel like a lot of work to do now when you&#39;ve written your code but this would help you and anyone who reads your code.

</details>



huangapple
  • 本文由 发表于 2020年9月29日 02:43:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64107871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定