英文:
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's really confusing in the way you'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'm suggesting, I know it might feel like a lot of work to do now when you've written your code but this would help you and anyone who reads your code.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论