我遇到了一些问题。我正在尝试编写一个简单的石头剪刀布游戏,并将主要函数放在 do while 循环中。一开始我要求用户输入字符串,然后生成程序移动的随机数,然后运行 if 语句来确定获胜者,最后我询问玩家是否愿意再次玩。第一个问题是,无论它告诉我什么输入,这都是损失。第二个是,当我第二次执行循环时,它会跳过用户输入,只向您提供丢失消息,而无需您采取任何行动。
这是代码:
import java.util.Scanner;
import java.util.Random;
public class RPS
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
char PA;
do
{
String RGW;
System.out.println("Rock Paper or Scissors?");
String PI = input.nextLine();
int RGrand.nextInt(3);
if(RG == 0)
{
RGW = "Rock";
}
else if(RG == 1)
{
RGW = "Paper";
}
else
{
RGW = "Scissors";
}
System.out.println("Opponents Move: " + RGW + "\nYour Move: " + PI);
if(PI == RGW)
{
System.out.println("It's a Tie!");
}
else if((PI == "Rock" && RGW == "Scissors") || (PI == "Scissors" && RGW == "Paper") || (PI == "Paper" && RGW == "Rock"))
{
System.out.println("You Win!");
}
else
{
System.out.println("You Lose!");
}
System.out.println("Play Again? Y/N");
PA = input.next().charAt(0);
}
while(PA == 89 || PA == 121);
}
}
对于失败消息,我尝试写出获胜、失败和平局条件的每种组合,并且我尝试说如果 userInput = oppInput 则为平局。它仍然只是告诉我这是一种损失。
对于跳过输入问题,我尝试将生成放在输入语句之后,并且尝试将其放入仅在用户输入不为空时才运行的 if 语句中。它仍然会跳过并直接进入丢失消息。
首先 String PI = input.nextLine();跳过第二个循环,因为 Scanner 类是 nextLine() 有时会跳过输入
所以尝试 next() 仅接受输入
我已经修复了代码,这是修复后的代码
import java.util.Scanner;
import java.util.Random;
public class RPS
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
char PA;
do
{
String RGW;
System.out.println("Rock Paper or Scissors?");
String PI = input.next();
int RG = rand.nextInt(3);
if(RG == 0)
{
RGW = "Rock";
}
else if(RG == 1)
{
RGW = "Paper";
}
else
{
RGW = "Scissors";
}
System.out.println("Opponents Move: " + RGW + "\nYour Move: " + PI);
if(PI.contentEquals(RGW))
{
System.out.println("It's a Tie!");
}
else if((PI.contentEquals("Rock") && RGW.contentEquals("Scissors")) || (PI.contentEquals("Scissors") && RGW.contentEquals("Paper")) || (PI.contentEquals("Paper") && RGW.contentEquals("Rock")))
{
System.out.println("You Win!");
}
else
{
System.out.println("You Lose!");
}
System.out.println("Play Again? Y/N");
PA = input.next().charAt(0);
}
while(PA == 89 || PA == 121);
}
}
在此代码中尝试处理用户输入,以便代码不会中断或显示无效输入的不同输出
为此使用输入验证,您的代码应该准备好进行一些游戏