gpt4 book ai didi

java - while 循环中第一个循环后的输出

转载 作者:行者123 更新时间:2023-12-01 18:43:07 24 4
gpt4 key购买 nike

我的问题不是关于一般游戏算法。当我对问题“您想继续吗?输入 true 或 false。”回答“true”时,程序输出:

"Player one, throw your shape(rock, paper, scissors)! 
Player two, throw your shape(rock, paper, scissors)!"

所以我可以在第一个周期输入值,但不能在第二个周期输入值。我该如何修复它?谢谢。

代码:

public static void main(String[] args) {

String playerOne;
String playerTwo;
Scanner myScan = new Scanner(System.in);
boolean playAgain = true;

do
{
System.out.println("Player one, throw your shape(rock, paper, scissors)! ");
playerOne = myScan.nextLine();
System.out.println("Player two, throw your shape(rock, paper, scissors)! ");
playerTwo = myScan.nextLine();




if (playerOne.equals("scissors") && playerTwo.equals("rock"))
{
System.out.println("Player one lost! Playr two won!");
}

else if (playerOne.equals("scissors") && playerTwo.equals("paper"))
{
System.out.println("Player one won! Player two lost!");
}


else if (playerOne.equals("rock") && playerTwo.equals("paper"))
{
System.out.println("Player one lost! Player two won!");
}


else if (playerOne.equals("rock") && playerTwo.equals("scissors"))
{
System.out.println("Player one won! Player two lost!");
}


else if (playerOne.equals("paper") && playerTwo.equals("scissors"))
{
System.out.println("Player one lost! Player two won!");
}


else if (playerOne.equals("paper") && playerTwo.equals("rock"))
{
System.out.println("Player one won! Player two lost!");
}

System.out.println("Do you want to continue? Enter true or false.");
playAgain = myScan.nextBoolean();

}while(playAgain);


}
}

最佳答案

这是因为 Scanner 仅读取您使用 nextBoolean 请求的 boolean 值,而不读取其他内容,甚至不读取以下行结尾。然后,结束行保留在输入流中,并在循环出现并且您请求 nextLine 时作为空行返回。

您需要做的是读取完整的一行,而不仅仅是 playAgain 的 boolean 值,并手动解释它(建议使用 myScan.nextLine() 之类的东西。等于("is"))。

关于java - while 循环中第一个循环后的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19063065/

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