我正在用java编写一个视频扑克,我需要询问玩家是否想要从他们的手中移除任何牌。我为此编写了一个 while 循环,但它现在没有按预期的方式工作。如果有人能引导我走向正确的方向,我将不胜感激——我对java还是新手..谢谢。 (计数器
的存在是为了让玩家不会移除超过 5 张牌)
String response = "y";
int counter = 0;
System.out.println("Remove any cards?");
System.out.println("Enter y for 'yes' and n for 'no'");
response = input.nextLine();
while((response != "n") && (counter < 5))
{
System.out.println("Enter the number of a card to be removed (1-5)");
int l = input.nextInt();
p.removeCard(p.getHand().get(l-1));
p.addCard(cards.deal());
cards.incrementTop();
counter ++;
System.out.println("Card removed. More? Type 'yes' or 'no'");
String answer = input.nextLine();
if (answer == "no")
{
response = "n";
}
}
最佳答案
您不能使用 !=
或 ==
比较字符串。
while(!("n".equals(response)) && (counter < 5))
这里也一样
if (answer == "no")
其他需要改进的地方
- 用户第一次可以写“不”,现在它无法工作
- 您要求用户写“no”,但您检查“n”
- N呢?是吗?
- 那nO呢?不? (提示:搜索
.equalsIgnoreCase()
)
给您的另一个提示:使用 boolean 变量表示是/否
,更好、更简单:)
关于Java while循环永远不会进入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22917457/