gpt4 book ai didi

java - 如何循环主类

转载 作者:行者123 更新时间:2023-12-01 18:39:44 25 4
gpt4 key购买 nike

如果用户想要但不确定如何,我正在尝试让我的石头剪刀布应用程序循环。我正在上编程课,但我在上次尝试修复代码时破坏了代码,并设法恢复到之前的状态。

public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String playAgain = "Y";

while (playAgain.equals("Y") || playAgain.equals("y"))
{
String playerChoice = "";
while (!playerChoice.equals("R") && !playerChoice.equals("P") && !playerChoice.equals("S"))
{
System.out.println("Please enter a correct character\n (R)ock, (P)aper, or (S)cissors.");
playerChoice = scan.next();

//Player choice to upper case to minimize the number of wrong inputs//
playerChoice = playerChoice.toUpperCase();
}

int randNum = (int) (Math.random() * 3);
String compChoice = "";
switch (randNum)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer chose: " + compChoice);

if (playerChoice.equals(compChoice))
{
System.out.println("It's a Tie!");
} else if (playerChoice.equals("R") && compChoice.equals("S") || playerChoice.equals("P") && compChoice.equals("R") || playerChoice.equals("S") && compChoice.equals("P"))
{
System.out.println("You Win!");
} else
{
System.out.println("You Lose");
}
System.out.println("Would you like to play again?\n(Y or N)");
playAgain = scan.nextLine();
if (playAgain.equals("N"))
{
break;
}
}
}

最佳答案

解决方案是您的扫描方法调用之间需要达成一致。

要么两者都应该是 nextLine,要么两者都应该是 next。

顺便说一句 - 我非常喜欢在字符串比较中使用 .equalsIgnoreCase 而不是 .equals,因为它使代码简单且易于阅读。 (例如,您可以跳过 toUpperCase 以及额外的条件)

<小时/>

至于扫描仪为什么/到底在做什么导致这个问题,这是更详细和复杂的。

关于java - 如何循环主类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59959770/

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