我必须创建一个虚拟摇滚剪刀纸游戏程序。我已经弄清楚了大部分内容,但是在用户每次进入游戏时要生成1-3的随机数时遇到了问题。我将在下面显示两个类,首先是用户,然后是计算机类。任何帮助将不胜感激,谢谢。
用户:
public String play()
{
do{
switch (userChoice) {
case R:
{
System.out.println("You have chosen rock.");
if (robot.getComputerChoice().equals(paper)){
System.out.println("You lose! \nPaper covers rock!");
numOfLosses ++;
}
else if (robot.getComputerChoice().equals(scissors)){
System.out.println("You win! \nRock smashes scissors!");
numOfWins ++;
}
else if (robot.getComputerChoice().equals(rock)){
System.out.println("Its a tie!");
numOfTies ++;
}
userChoice = result;
}
break;
case P:
{
System.out.println("You have chosen paper.");
if (robot.getComputerChoice().equals(rock)){
System.out.println("You win! \nPaper covers rock!");
numOfWins ++;
}
else if (robot.getComputerChoice().equals(scissors)){
System.out.println("You lose! \nScissors cuts paper!");
numOfLosses ++;
}
else if (robot.getComputerChoice().equals(paper)){
System.out.println("Its a tie!");
numOfTies ++;
}
userChoice = result;
}
break;
case S:
{
System.out.println("You have chosen scissors.");
if (robot.getComputerChoice().equals(rock)){
System.out.println("You lose! \nRock smashes scissors!");
numOfLosses ++;
}
else if (robot.getComputerChoice().equals(paper)){
System.out.println("You win! \nScissors cuts paper!");
numOfWins ++;
}
else if (robot.getComputerChoice().equals(scissors)){
System.out.println("Its a tie!");
numOfTies ++;
}
userChoice = result;
}
break;
default:
System.out.println("That input was invalid.");
break;
}
Scanner scan = new Scanner(System.in);
System.out.println("Lets play Rock, Paper, Sciccors!");
System.out.println("(R)ock, (P)aper, or (S)cissors? 0 to end the game.");
userChoice = scan.next();
userChoice = userChoice.toUpperCase();
} while (!userChoice.equals(EXIT));
System.out.println("Thanks for playing!");
System.out.println("Number of wins: " + numOfWins + "\nNumber of losses: "
+ numOfLosses + "\nNumber of ties: " + numOfTies);
total = numOfWins + numOfLosses + numOfTies;
winPercentage = (numOfWins/total) * 100;
System.out.printf(userName + "'s win percentage: %.2f", winPercentage);
System.out.print("%");
return result;
计算机:
public Computer() {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
COMPUTERNAME = "Bob";
while (){ // can't figure out what to do here.
generateNumber = rand.nextInt(3)+1; // 1 to 3
switch (generateNumber) {
case 1:
computerChoice = "rock";
break;
case 2:
computerChoice = "paper";
break;
case 3:
computerChoice = "scissors";
break;
default:
break;
}
}
}
public String getComputerChoice()
{
return computerChoice;
}
public String getComputerName()
{
System.out.print("My name is ");
System.out.print(COMPUTERNAME);
System.out.println(", your computer opponent.");
return COMPUTERNAME;
}