gpt4 book ai didi

Java Do While 无法正常工作

转载 作者:行者123 更新时间:2023-12-01 20:56:38 26 4
gpt4 key购买 nike

抱歉,我是这个网站的新手,所以不确定它会如何显示。我正在尝试制作一个简单的石头剪刀布游戏。在 while 语句之后,如果没有输入 R、P、S,则程序不执行任何操作。我希望它循环回到开头的问题,以便可以输入正确的选择。另外,我如何输入“无效选择,请重试”之类的打印语句?

package rps.gameapp;

import java.util.Scanner;

public class RPSGameApp
{

public static void main(String[] args)
{

Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int randNum = (int) (Math.random() * 3);

do
{
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));


String compChoice = "";
switch (randNum)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}

System.out.println("The computer entered \"" + compChoice + "\".");

if (compChoice.equalsIgnoreCase(userChoice))
{
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase(userChoice)
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P"))
{
System.out.println("User Wins");
} else
{
System.out.println("User Loses");
}

System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();

} while (playAgain.equalsIgnoreCase("Y"));

System.out.println("Thanks for Playing!");

}
}

最佳答案

看起来您忘记了内部 do while 循环的一个 do

应该是:

do {
do {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P") && !userChoice.equalsIgnoreCase("R") && !userChoice.equalsIgnoreCase("S"));
...
} while (playAgain.equalsIgnoreCase("Y"));

如果没有内部 do (以及围绕该循环主体的花括号),内部循环将成为一个具有空主体的 while 循环。

关于Java Do While 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42245923/

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