gpt4 book ai didi

java - 石头、剪刀、布-BlueJ 疯狂循环

转载 作者:行者123 更新时间:2023-12-01 08:51:53 28 4
gpt4 key购买 nike

以下是我在 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;
}
}

最佳答案

这两行是问题所在:

String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false) {

您正在阅读一行,然后一遍又一遍地检查该行。您需要在循环内读取新行。按照你现在的方式,它只是试图无数次地重复相同的 Action 。

尝试:

String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false) {

//do all of the stuff that is already inside your loop

playerChoice = scan.nextLine();
}

每次处理最后一个输入后,这都会再次获取用户输入。

关于java - 石头、剪刀、布-BlueJ 疯狂循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42334370/

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