以下是我在BlueJ的摇滚,纸张,剪刀游戏的代码。当我编译并且用户输入输入时,计算机立即从playerWins()打印许多输出。当用户输入"退出"时,游戏结束。有人可以帮助我,所以我的屏幕不会被淹没吗? (如果有任何方法可以压缩我的代码也会很棒)。
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors
{
public static void main(String[] args)
{
int wins = 0, losses = 0, ties = 0;
boolean output;
Scanner scan = new Scanner(System.in);
System.out.print("(R)ock, (P)aper, (S)cissors, or quit: ");
String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false)
{
playerChoice = playerChoice.toUpperCase();
String computerChoice = getComputerChoice();
if(playerChoice.equals(computerChoice) != true)
{
output = playerWins(playerChoice, computerChoice);
if (output == true)
{
wins++;
}
else if (output == false)
{
losses++;
}
}
else
{
ties++;
System.out.println("Tie!");
}
}
System.out.println("QUIT");
System.out.println("Wins: " + wins);
System.out.println("Losses: " + losses);
System.out.println("Ties: " + ties);
scan.close();
}
public static String getComputerChoice()
{
Random gen = new Random();
int num = gen.nextInt(30) + 1;
if (num % 3 == 2)
{
return "R";
}
else if (num % 3 == 1)
{
return "P";
}
else
{
return "S";
}
}
public static boolean playerWins(String playerChoice, String computerChoice)
{
if (playerChoice.equals("R") == true)
{
if (computerChoice.equals("P") == true)
{
System.out.println("My Point! \nP beats R"); // Rock is beaten by paper
return false;
}
else if (computerChoice.equals("S") == true)
{
System.out.println("Your Point! \nR beats S"); // Rock beats scissors
return true;
}
}
else if (playerChoice.equals("P") == true)
{
if (computerChoice.equals("R") == true)
{
System.out.println("Your Point! \nP beats R"); //Paper beats rock
return true;
}
else if (computerChoice.equals("S") == true)
{
System.out.println("My Point! \nS beats P"); //Paper is beaten by scissors
return false;
}
}
else if (playerChoice.equals("S") == true)
{
if (computerChoice.equals("P") == true)
{
System.out.println("Your Point! \nS beats P"); //Scissor beats paper
return true;
}
else if (computerChoice.equals("R") == true)
{
System.out.println("My Point! \nR beats S"); //Scissors is beaten by rock
return false;
}
}
return false;
}
}
答案 0 :(得分:1)
这两行是问题所在:
String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false) {
您正在阅读一行,然后一遍又一遍地检查该行。您需要在循环中读取内部的新行。你现在拥有它的方式,只是试图无限次地进行相同的移动。
尝试:
String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false) {
//do all of the stuff that is already inside your loop
playerChoice = scan.nextLine();
}
每次处理完最后一次输入后,这将再次获得用户输入。
答案 1 :(得分:0)
您只检查用户输入一次,即在循环之前:
String playerChoice = scan.nextLine();
解决这个问题的一个非常好的方法如下:
String playerChoice;
while((playerChoice = scan.nextLine()).equals("quit") == false)
{
//more code
}
上述代码的作用是playerChoice
在调用.equals("quit")
之前设置。如果你使用这种方法,你不需要在循环结束时再设置一行来设置playerChoice
,而只需在循环的头部进行。