简体   繁体   English

石头,剪刀,Java游戏

[英]Rock, Paper, Scissors Java Game

My assignment is to write a program that lets the user play the game of Rock, Paper, Scissors against the computer. 我的任务是编写一个程序,使用户可以在计算机上玩摇滚,剪纸,剪刀游戏。

Instructions: 说明:

The main method should have two nested loops, where the outer loop will allow the user to play the game as often as desired and the inner loop will play the game as long as there is a tie. main方法应具有两个嵌套循环,其中外循环将允许用户根据需要频繁地玩游戏,而内循环将在有平局的情况下玩游戏。 Call the method isValidChoice() in a while loop in the userChoice() method to verify that the choice that user enters must be “rock”, “paper”, or “scissors”. 在userChoice()方法的while循环中调用方法isValidChoice(),以验证用户输入的选择必须是“石头”,“纸”还是“剪刀”。 If invalid string is input, isValidChoice()will return false and the program should ask for new input until the valid input is given. 如果输入了无效的字符串,则isValidChoice()将返回false,程序应要求新输入,直到给出有效输入为止。

Situation: 情况:

The program runs fine when the user enters a valid input. 当用户输入有效输入时,程序运行正常。 However once its not a valid input, there is a small problem. 但是,一旦它不是有效的输入,就会有一个小问题。

Result: 结果:

Enter rock, paper, or scissors: rocky
Invalid input, enter rock, paper, or scissors: roc
Invalid input, enter rock, paper, or scissors: rock
The computer's choice was paper
The user's choice was rocky

Play again? (y/n)

As you can see, the program recognizes the invalid inputs. 如您所见,程序会识别无效的输入。 The user finally enter a valid input the third time. 用户最终第三次输入有效输入。 However, it displays user's first choice "rocky" which is invalid. 但是,它显示用户的首选“ rocky”,这是无效的。 Therefore the program can't display who wins. 因此,该程序无法显示谁获胜。

Question

I need your help. 我需要你的帮助。
I want my program to run like this: When the user enters multiple invalid inputs, but once a valid input is entered, my program should still be able to display the user's valid input and display the winner. 我希望程序运行如下:当用户输入多个无效输入,但是输入有效输入后,我的程序仍应能够显示用户的有效输入并显示获胜者。

import java.util.Scanner;
import java.util.Random;

public class RockPaperScissorsGame 
{
   public static void main (String[] args)
   {
      Scanner keyboard = new Scanner(System.in);

      String computer, user;
      char keepPlaying;

      do 
      {
         computer = computerChoice();
         user = userChoice();

         System.out.println("The computer's choice was " + computer);
         System.out.println("The user's choice was " + user);

         determineWinner(computer, user);

         while (computer.equals(user))
         {
            computer = computerChoice();
            user = userChoice();

            System.out.println("The computer's choice was " + computer);
            System.out.println("The user's choice was " + user);

            determineWinner(computer, user);
         }


         System.out.println("\n" + "Play again? (y/n)");
         keepPlaying = keyboard.nextLine().toLowerCase().charAt(0);

         while ( keepPlaying != 'y' && keepPlaying != 'n' )
         {
            System.out.println("Invalid input, please enter (y/n)");
            keepPlaying = keyboard.nextLine().toLowerCase().charAt(0);
         }

      } while (keepPlaying == 'y');

   }
   public static String computerChoice()
   {
      String[] choice = {"rock","paper","scissors"};
      Random rand = new Random();
      int computerChoice = rand.nextInt(3);
      return choice[computerChoice];
   }
   public static String userChoice()
   {
      Scanner keyboard = new Scanner(System.in);
      System.out.print("Enter rock, paper, or scissors: ");
      String choice = keyboard.nextLine();

      isValidChoice(choice);
      return choice;
   }
   public static boolean isValidChoice (String choice)
   {
      Scanner keyboard = new Scanner(System.in);

      while (!(choice.equalsIgnoreCase("rock")) && !(choice.equalsIgnoreCase("paper")) && !(choice.equalsIgnoreCase("scissors")))
    {
       System.out.print("Invalid input, enter rock, paper, or scissors: ");
       choice = keyboard.nextLine();
    }

       return true;
    }
    public static void determineWinner(String computer, String user)
    {
       if (computer.equalsIgnoreCase("rock") && user.equalsIgnoreCase("paper"))
          System.out.println("\n" + "Paper wraps rock.\nThe user wins!");
       else if (computer.equalsIgnoreCase("rock") && user.equalsIgnoreCase("scissors"))
          System.out.println("\n" + "Rock smashes scissors.\nThe computer wins!");
       else if (computer.equalsIgnoreCase("paper") && user.equalsIgnoreCase("rock"))
          System.out.println("\n" + "Paper wraps rock.\nThe computer wins!");
       else if (computer.equalsIgnoreCase("paper") && user.equalsIgnoreCase("scissors"))
          System.out.println("\n" + "Scissors cuts paper.\nThe user wins!");
       else if (computer.equalsIgnoreCase("scissors") && user.equalsIgnoreCase("rock"))
          System.out.println("\n" + "Rock smashes scissors.\nThe user wins!");
       else if (computer.equalsIgnoreCase("scissors") && user.equalsIgnoreCase("paper"))
          System.out.println("\n" + "Scissors cuts paper.\nThe computer wins!");
       else if (computer.equalsIgnoreCase(user))
          System.out.println("\n" + "The game is tied!\nGet ready to play again...");
    }   
}

This issue arises from the fact that Java is pass by value, not pass by reference. 此问题源于Java是按值传递而不是按引用传递的事实。

In other words, rather than a reference of your parameter being passed to the method, a copy of the parameter is passed. 换句话说,传递的不是参数的引用,而是传递给方法的副本。 Your method changes the copy but then once the method ends, the copy goes out of scope and is garbage collected. 您的方法更改了副本,但是一旦方法结束,副本就会超出范围并被垃圾回收。

When you pass choice into isvalidChoice , the reference to choice itself isn't passed. 当您将choice传递给isvalidChoice ,不会传递对选择本身的引用。 A copy of the string is made and then is passed. 复制字符串,然后将其传递。 When you update the variable choice, it doesn't change the original string, it changes the copy that the System made. 更新变量选择时,它不会更改原始字符串,而是会更改系统创建的副本。 This answer explains how it works pretty well. 这个答案解释了它如何很好地工作。

So what should you do? 那你该怎么办?

Instead of looping in isValidChoice have isValidChoice return false if it isn't a valid input. 如果不是有效的输入, isValidChoice使用isValidChoice返回false来代替isValidChoice的循环。

Your isValidChoice should end up looking like this: 您的isValidChoice应该最终看起来像这样:

public static boolean isValidChoice(String choice) {
    return (choice.equalsIgnoreCase("rock")) || (choice.equalsIgnoreCase("paper")) || (choice.equalsIgnoreCase("scissors"));
}

Then do something like this in userChoice 然后在userChoice做这样的事情

Scanner keyboard = new Scanner(System.in);
while(!isValidChoice(choice)) {
    System.out.print("Invalid input, enter rock, paper, or scissors: ");
    choice = keyboard.nextLine();
}

package practicePrograms; 打包练习程序;

import java.util.Random; 导入java.util.Random; import java.util.Scanner; 导入java.util.Scanner;

public class Rock_Paper_Scissors { 公共类Rock_Paper_Scissors {

@SuppressWarnings({ "resource" })
public static void main(String[] args) {
    Random rand = new Random();
    Scanner scan = new Scanner (System.in);
    int totalscuser = 0;
    int compans = 0;
    int totalsccpu = 0;
    System.out.println("Rock Paper Scissors!"+"\n"+"Rock:     '0'"+ "\n" +"Paper:    '1'"+"\n"+"Scissors: '2'");
    System.out.println("It's best out of 3!");
    for(int i = 0; i<3; i++){
        compans = rand.nextInt(3);
        compans = rand.nextInt(3);
        int inp = scan.nextInt();
        if(inp == compans){
            System.out.println("Tie");
        }else if((inp-1) == compans){
            if(inp>2){
                System.err.println("Enter a valid input."+"\n"+"CPU Wins because user entered an invalid input.");
                totalsccpu = totalsccpu + 1;
            }else{
                System.out.println("User Wins");
                totalscuser = totalscuser + 1;
            }
        }else if((inp) == compans-1){
            if(inp>2){
                System.err.println("Enter a valid input."+"\n"+"CPU Wins because user entered an invalid input.");
                totalsccpu = totalsccpu + 1;
            }else{
            System.out.println("CPU Wins");
            totalsccpu = totalsccpu + 1;
            }
        }else if((inp-2) == compans){
            if(inp>2){
                System.err.println("Enter a valid input."+"\n"+"CPU Wins because user entered an invalid input.");
                totalsccpu = totalsccpu + 1;
            }else{
            System.out.println("CPU Wins");
            totalsccpu = totalsccpu + 1;
            }
        }else if((inp) == compans-2){
            if(inp>2){
                System.err.println("Enter a valid input."+"\n"+"CPU Wins because user entered an invalid input.");
                totalsccpu = totalsccpu + 1;
            }else{
                System.out.println("User Wins");
                totalscuser = totalscuser + 1;
            }
        }else{
            System.err.println("Enter a valid input."+"\n"+"CPU Wins because  user entered an invalid input.");
            totalsccpu = totalsccpu + 1;
        }
        System.out.println("CPU entered: "+compans);
    }
    if(totalsccpu>totalscuser){
        System.err.println("YOU LOSE! :(");
    }else if(totalsccpu<totalscuser){
        System.err.println("YOU WIN! :]");
    }if(totalsccpu == totalscuser){
        System.err.println("YOU TIED! :|");
    }
}

} }

This is example using integers, but can be adapted to your liking with strings. 这是使用整数的示例,但可以根据您的喜好使用字符串进行调整。

when I write {rock} it means it is your int identifier for rock, or use .equals(insert string identifier here) for string it will look like !user.equals("Rock") && !user.equals("Paper") && !user.equals("Scissors") 当我写{rock}时,它表示它是岩石的int标识符,或使用.equals(在此处插入字符串标识符)作为字符串,它看起来像!user.equals(“ Rock”)&&!user.equals(“ Paper” )&&!user.equals(“剪刀”)

while(user!= {rock} && user!= {paper} && user!= {scissors})
        { // use while
            System.out.print("Invalid choice! (Choose 1, 2 or 3): ");
            user= keyboard.nextInt(); // or keyboard.next() for any other way string
                if(user==1 || user==2 || user==3) // I used int for example
                    break; // quits the loop if proper identifier entered

            System.out.println();
            // if invalid choice, it will go back to the start of loop
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM