我的问题不是关于一般游戏算法。当我对“你想继续吗?输入真或假”这个问题回答“是”时,程序输出:
"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);
}
}
答案 0 :(得分:4)
这是因为Scanner
只读取您使用nextBoolean
请求的布尔值,而不是其他任何内容,甚至不是以下行结束。然后结束的行保留在输入流中,并在循环出现时作为空行返回,并且您要求nextLine
。
您要做的是读取完整的行而不仅仅是playAgain
的布尔值,并手动解释(建议使用类似myScan.nextLine().equals("yes")
的内容)。