gpt4 book ai didi

java - while 循环中的奇怪行为

转载 作者:行者123 更新时间:2023-12-01 10:40:42 26 4
gpt4 key购买 nike

我正在编写一个在二十一点中轮流的函数。它看起来像这样:

public void takeTurn(Deck deck) {
Scanner reader = new Scanner(System.in);
String response = "y";
while (response.toLowerCase().equals("y")) {
System.out.print("Would you like another card? (Y or N) ");
response = reader.nextLine();
if (response.toLowerCase().equals("y")) {
hand.getCards().add(deck.getTopCard());
System.out.println("Current hand: " + hand);
if (hand.getValue() > 21) {
System.out.println("You busted with " + hand.getValue());
break;
}
}
}
}

奇怪的是,当我输入“n”时,它没有再抽一张牌,但它确实重新提示我。然后我放入了一个 printLine 语句,如下所示:

public void takeTurn(Deck deck) {
Scanner reader = new Scanner(System.in);
String response = "y";
while (response.toLowerCase().equals("y")) {
System.out.println("response is " + response);
System.out.print("Would you like another card? (Y or N) ");
response = reader.nextLine();
if (response.toLowerCase().equals("y")) {
hand.getCards().add(deck.getTopCard());
System.out.println("Current hand: " + hand);
if (hand.getValue() > 21) {
System.out.println("You busted with " + hand.getValue());
break;
}
}
}
}

这是一个示例交互:

response is y
Would you like another card? (Y or N) n
response is y
Would you like another card? (Y or N)

第一个“响应是 y”是有道理的。第二个我无法解释。

有什么想法吗?

最佳答案

public static void main(String[] args) {
takeTurn(new Scanner(System.in)); // just an example how you share a single Scanner as a parameter when calling takeTurn function
}

public static void takeTurn(Scanner sc/*, Deck deck*/) { // static may be removed if you do not use the function within static main void
if (isYResponse(sc, "Would you like another card? (Y or N) ")) {
System.out.println("response is y");
/*
hand.getCards().add(deck.getTopCard());
System.out.println("Current hand: " + hand);
if (hand.getValue() > 21) {
System.out.println("You busted with " + hand.getValue());
}
*/
} else {
System.out.println("response is n");
}
takeTurn(sc/*, deck.next()*/); // be careful with this loop: define when it stops actually... when isGameOver(), for example?
}

private static boolean isYResponse(Scanner sc, String message) { // static may be removed if you do not use the function within static main void
System.out.print(message);
String response;
if ((response = sc.nextLine()).isEmpty()) {
response = sc.nextLine();
}
return ("y".compareToIgnoreCase(response) == 0)
? true
: (("n".compareToIgnoreCase(response) == 0)
? false
: isYResponse(sc, message));
}
<小时/>

附注抱歉:我不知道其他类的结构,例如 Deck。如果您有这种想法,我只是希望我的回答能够帮助您找到所需的最终具体解决方案。

关于java - while 循环中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34425488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com