【问题标题】:How to loop a certain area of code after a wrong user input? (Java)用户输入错误后如何循环某个区域的代码? (爪哇)
【发布时间】:2016-12-03 01:57:49
【问题描述】:

我一直在用 Java 开发一个小型的剪刀石头布游戏,其中输赢的条件取决于计算机或玩家是否赢得了五场比赛。如果输入错误,我不确定如何让程序在用户输入处循环。

这是我遇到此问题的代码

我要循环的部分是带有“else if (determination.equals("Y")) {"的部分

import java.util.*;

public class Rock_Paper_Scissors {

  public static void main(String arg[]) {
    boolean loopGameStart = true;

    while (loopGameStart) {
      System.out.println("Welcome to Rock Paper Scissors, a game programmed "
                       + "by Daniel Park. Would you like to start? (Y/N)");
      Scanner userInput = new Scanner(System.in);
      String determination = userInput.next();

      if (determination.equals("N")) {
        System.out.println("Please, do reconsider...");
        loopGameStart = true;
      } else if (determination.equals("Y")) {
        Random rand = new Random();
        int n = rand.nextInt(3) + 1;
        // 1 = Rock, 2 = Paper, 3= Scissor
        int humanWinCount = humanWinCount();
        int computerWinCount = computerWinCount();
        System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
        Scanner userRPS = new Scanner(System.in);
        int choiceRPS = userRPS.nextInt();
        while ((humanWinCount < 5) && (computerWinCount < 5)) {
          if (choiceRPS == 0) {
            if (n == 1) {
              System.out.println("TIE!!");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            } else if (n == 2) {
              System.out.println("LOSS!!");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              computerWinCount = computerWinCount + 1;
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            } else if (n == 3) {
              System.out.println("WIN!!");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              humanWinCount = humanWinCount + 1;
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            } else {
              System.out.println("I do not understand... Try Again.");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            }
          } else if (choiceRPS == 1) {
            if (n == 1) {
              System.out.println("WIN!!");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              humanWinCount = humanWinCount + 1;
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            } else if (n == 2) {
              System.out.println("TIE!!");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            } else if (n == 3) {
              System.out.println("LOSS!!");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              computerWinCount = computerWinCount + 1;
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            } else {
              System.out.println("I do not understand... Try again.");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            }
          } else if (choiceRPS == 2) {
            if (n == 1) {
              System.out.println("LOSS");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              computerWinCount = computerWinCount + 1;
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            } else if (n == 2) {
              System.out.println("WIN!!");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              humanWinCount = humanWinCount + 1;
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            } else if (n == 3) {
              System.out.println("TIE!!");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            } else {
              System.out.println("I do not understand... Try again.");
              System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
              System.out.println("Computer: " + computerWinCount + " rounds won");
              System.out.println("You: " + humanWinCount + " rounds won");
              choiceRPS = userRPS.nextInt();
            }
          }
        }

        if (humanWinCount == 5) {
          System.out.println("Congratulations, you win!!");
          System.out.println("Computer: " + computerWinCount + " rounds won");
          System.out.println("You: " + humanWinCount + " rounds won");
          System.out.println("Would you like to try again? (Y/N)");
          Scanner continueOrNot = new Scanner(System.in);
          String contOrNot = continueOrNot.next();
          if (contOrNot.equals("Y")) {
            loopGameStart = true;
          } else if (contOrNot.equals("N")) {
            System.out.println("Okay, goodbye!!");
            loopGameStart = false;
          }
        }

        if (computerWinCount == 5) {
          System.out.println("Boohoo, you lost!!");
          System.out.println("Computer: " + computerWinCount + " rounds won");
          System.out.println("You: " + humanWinCount + " rounds won");
          System.out.println("Would you like to try again? (Y/N)");
          Scanner continueOrNot = new Scanner(System.in);
          String contOrNot = continueOrNot.next();
          if (contOrNot.equals("Y")) {
            loopGameStart = true;
          } else if (contOrNot.equals("N")) {
            System.out.println("Okay, goodbye!!");
            loopGameStart = false;
          }
        }
      } else {
        System.out.println("I do not understand, please try again!");
      }
    }
  }

  public static int humanWinCount() {
      int x = 0;
      return x;
  }

  public static int computerWinCount() {
      int c = 0;
      return c;
  }
}

【问题讨论】:

  • P.S. humanWinCount()computerWinCount() 将永远是 return 0
  • 您不需要创建多个扫描仪对象。只维护一个。无论如何,由于它们都在使用“System.in”,如果你关闭其中一个,它们都会被关闭。所以,最好只有一个对象,在完整的程序中使用它。
  • 我建议您将一些(或者更确切地说,大部分)代码提取到方法中,这样您就不会重复自己。也可以尝试使用常量。

标签: java


【解决方案1】:

请不要将所有内容都写在一个主函数中,或者在任何地方重复相同的代码,等等。

我完全重建了您的代码,还实现了建议的循环@Austin。现在你应该像你一样工作,或者非常接近。享受:

import java.util.*;

public class Rock_Paper_Scissors
{
    public static void main( String arg[] )
    {
        Rock_Paper_Scissors game = new Rock_Paper_Scissors();
        game.startLogic();
    }

    private Random  rand;
    private Scanner inputScanner;
    private boolean loopGameStart;

    private int humanWinCount;
    private int computerWinCount;

    public Rock_Paper_Scissors()
    {
        this.rand          = new Random();
        this.inputScanner  = new Scanner( System.in );
        this.loopGameStart = true;

        humanWinCount    = 0;
        computerWinCount = 0;
    }

    public void startLogic()
    {
        System.out.print( "Welcome to Rock Paper Scissors, a game programmed by Daniel Park. " );
        this.askUntilGetAnAnswer( "N" );
    }

    private int humanWinCount()
    {
        int x = 0;
        return x;
    }

    private int computerWinCount()
    {
        int c = 0;
        return c;
    }

    private void askUntilGetAnAnswer( String determination )
    {
        while( this.loopGameStart )
        {
            if( !determination.equals( "Y" ) )
            {
                System.out.println( "\nWould you like to start? (Y/N)" );
                determination = this.inputScanner.next();
            }

            if( determination.equals( "N" ) )
            {
                System.out.println( "Please, do reconsider..." );
                this.loopGameStart = false;
            }
            else if( determination.equals( "Y" ) )
            {
                this.processCoreGameLogic();
            }
            else
            {
                System.out.print( "I do not understand, please try again!" );
            }
        }
    }

    private void processCoreGameLogic()
    {
        int choiceRPS;
        System.out.println( "Choose 0, 1, or 2 (Rock/Paper/Scissor)" );

        // 1 = Rock, 2 = Paper, 3= Scissor
        this.humanWinCount    = this.humanWinCount();
        this.computerWinCount = this.computerWinCount();

        while( ( this.humanWinCount < 5 ) && ( this.computerWinCount < 5 ) )
        {
            try
            {
                choiceRPS = inputScanner.nextInt();

                if( choiceRPS >= 0 && choiceRPS <= 2 )
                {
                    this.playing( choiceRPS );
                }
            }
            catch( InputMismatchException e )
            {
                System.out.print( "I do not understand, please try again!" );
                inputScanner.next();
            } 

        }

        this.endGame();
    }

    private void endGame()
    {
        String contOrNot = "";

        if( this.humanWinCount == 5 )
        {
            System.out.println( "\nCongratulations, you win!!" );
            System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
            System.out.println( "You: " + this.humanWinCount + " rounds won" );
            System.out.println( "Would you like to try again? (Y/N)" );

            contOrNot = this.inputScanner.next();
        }

        if( this.computerWinCount == 5 )
        {
            System.out.println( "\nBoohoo, you lost!!" );
            System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
            System.out.println( "You: " + this.humanWinCount + " rounds won" );
            System.out.println( "Would you like to try again? (Y/N)" );

            contOrNot = this.inputScanner.next();
        }

        if( contOrNot.equals( "N" ) )
        {
            System.out.println( "Okay, goodbye!!" );
            this.loopGameStart = false;
        }
        else
        {
            askUntilGetAnAnswer( contOrNot );
        }
    }

    private void playing( int choiceRPS )
    {
        int randomInteger = this.rand.nextInt( 3 ) + 1;

        // choiceRPS 0 -> tie  1, loss 2, win  3
        // choiceRPS 1 -> win  3, tie  1, loss 2
        // choiceRPS 2 -> loss 2, win  3, tie  1
        //
        switch( choiceRPS*3 + randomInteger )
        {
            case 1:
            case 5:
            case 9:
            {
                show_tie();
                break;
            }
            case 2:
            case 6:
            case 7:
            {
                show_loss();
                break;
            }
            case 3:
            case 4:
            case 8:
            {
                show_win();
                break;
            }
            default:
            {
                System.out.println( "    I do not understand... Try again." );
                System.out.println( "    Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
                System.out.println( "    Computer: " + this.computerWinCount + " rounds won" );
                System.out.println( "    You: " + this.humanWinCount + " rounds won" );
            }
        }
    }

    private void show_loss()
    {
        System.out.println( "LOSS" );
        System.out.println( "Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
        this.computerWinCount = this.computerWinCount + 1;
        System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
        System.out.println( "You: " + this.humanWinCount + " rounds won" );
    }

    private void show_win()
    {
        System.out.println( "WIN!!" );
        System.out.println( "Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
        this.humanWinCount = this.humanWinCount + 1;
        System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
        System.out.println( "You: " + this.humanWinCount + " rounds won" );
    }

    private void show_tie()
    {
        System.out.println( "TIE!!" );
        System.out.println( "Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
        System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
        System.out.println( "You: " + this.humanWinCount + " rounds won" );
    }
}

【讨论】:

  • 哦,非常感谢。由于您提出的确切问题,我一直在考虑尝试重写此代码。我还在学习java,甚至我看到代码变得多么冗余:/
  • 虽然你很高兴重写整个程序,但我不认为这是stackoverflow的目标。我不认为,Perambulation 学到了很多这个答案......
【解决方案2】:

你可以使用 do while

int choiceRPS;
 do{
    choiceRPS = userRPS.nextInt();
}while(choiceRPS<0||choiceRPS>2);

【讨论】:

  • 那么,在我的代码中会是什么样子?我会在 int choiceRPS = userRPS.nextInt(); 之后移动我所做的一切吗?结束了吗?
  • 当你使用 do while 时,do 中的每件事都将至少运行一次,如果 while 的条件不满足,所以如果我输入 3,循环将只运行do while 需要缩进
  • 现在我已经这样做了,代码给了我一个错误,因为choiceRPS 的值现在超出了范围......
  • 我修复了它,只需要在循环外初始化choiceRPS。
  • @Perambulation 检查条件。这显然是这里最简单的解决方案。基本上,询问输入值是否为&lt; 0 or &gt; 2(并且至少询问一次)
【解决方案3】:

你的逻辑看起来很复杂。它可以很容易地简化,因为除了平局之外,游戏只有 3 个结果。

剪刀胜过纸

PAPER 击败 ROCK

ROCK 击败 SCISSORS

因此将输入视为分别代表 Rock、Paper 和 Scissors 的 0、1 和 2:

  1. 您需要跟踪两个数字。一是用户输入的选择 我们称它为userChoice,另一个叫computerChoice 是电脑的播放选择。这个computerChoice 应该是 随机选择的数字介于 0 和 2 之间。
  2. 现在,开始比较两个数字以确定获胜者和 增加相应的计数器(humanWinCountcomputerWinCount)。
  3. 当用户或 计算机至少赢得 5 轮比赛。

因此,您的游戏循环应该如下所示:

while(true){
            System.out.println();
            /*
             * If either one wins, break out of the game
             * and decide the winner.
             */
            if(humanWinCount == 5 || computerWinCount == 5){
                break;
            }
            System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
            //Read user's choice
            int userChoice = Integer.parseInt(sc.nextLine());
            //Computer will play it's turn
            int computerChoice = rand.nextInt(3);

            //Start comparing player's choice vs Computer's choice
            if(userChoice == computerChoice){
                tieCount++;
                showTieMessage();
            }else if(userChoice == 0 && computerChoice == 1){
                //User plays ROCK and computer plays PAPER 
                computerWinCount++;
                showComputerWinMessage();
            }else if(userChoice == 0 && computerChoice == 2){
                //User plays ROCK and computer plays SCISSORS
                humanWinCount++;
                showHumanWinMessage();
            }else if(userChoice == 1 && computerChoice == 0){
                //User plays PAPER and computer plays ROCK
                humanWinCount++;
                showHumanWinMessage();
            }else if(userChoice == 1 && computerChoice == 2){
                //User plays PAPER and computer plays SCISSORS 
                computerWinCount++;
                showComputerWinMessage();
            }else if(userChoice == 2 && computerChoice == 0){
                //User plays SCISSORS and computer plays ROCK
                computerWinCount++;
                showComputerWinMessage();
            }else if(userChoice == 2 && computerChoice == 1){
                //User plays SCISSORS and computer plays PAPER
                humanWinCount++;
                showHumanWinMessage();
            }else{
                System.out.println("Unrecougnized user input!!");
                System.out.println("Please Enter correct values!!");
                continue;
            }
        }

整个改造后的代码应该是这样的:

public class RockPepperScissor {
    private Random rand;
    private int humanWinCount;
    private int computerWinCount;
    private int tieCount; //Not Required, but still keeping in track.

    public RockPepperScissor(){
        rand = new Random();
        humanWinCount = 0;
        computerWinCount = 0;
        tieCount = 0;
    }

    public void startGame(){
        Scanner sc = new Scanner(System.in);
        System.out.println("Welcome to Rock Paper Scissors, a game programmed by Daniel Park. Would you like to start? (Y/N)");
        String userChoice = sc.nextLine();
        if(userChoice.equalsIgnoreCase("Y")){
            startGameLogic(sc);
        }else{
            if(userChoice.equalsIgnoreCase("N")){
                System.out.println("Do you want to reconsider?? (Y/N)");
                String secondChance = sc.nextLine();
                if(secondChance.equalsIgnoreCase("Y")){
                    startGameLogic(sc);
                }else{
                    System.exit(0);
                }
            }else{
                System.out.println("Unable to identify your input!! Stopping the game!!");
                System.exit(0);
            }
        }
        sc.close();
    }

    public void startGameLogic(Scanner sc){
        while(true){
            System.out.println();
            /*
             * If either one wins, break out of the game
             * and decide the winner.
             */
            if(humanWinCount == 5 || computerWinCount == 5){
                break;
            }
            System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
            //Read user's choice
            int userChoice = Integer.parseInt(sc.nextLine());
            //Computer will play it's turn
            int computerChoice = rand.nextInt(3);

            //Start comparing player's choice vs Computer's choice
            if(userChoice == computerChoice){
                tieCount++;
                showTieMessage();
            }else if(userChoice == 0 && computerChoice == 1){
                //User plays ROCK and computer plays PAPER 
                computerWinCount++;
                showComputerWinMessage();
            }else if(userChoice == 0 && computerChoice == 2){
                //User plays ROCK and computer plays SCISSORS
                humanWinCount++;
                showHumanWinMessage();
            }else if(userChoice == 1 && computerChoice == 0){
                //User plays PAPER and computer plays ROCK
                humanWinCount++;
                showHumanWinMessage();
            }else if(userChoice == 1 && computerChoice == 2){
                //User plays PAPER and computer plays SCISSORS 
                computerWinCount++;
                showComputerWinMessage();
            }else if(userChoice == 2 && computerChoice == 0){
                //User plays SCISSORS and computer plays ROCK
                computerWinCount++;
                showComputerWinMessage();
            }else if(userChoice == 2 && computerChoice == 1){
                //User plays SCISSORS and computer plays PAPER
                humanWinCount++;
                showHumanWinMessage();
            }else{
                System.out.println("Unrecougnized user input!!");
                System.out.println("Please Enter correct values!!");
                continue;
            }
        }

    }

    public void showHumanWinMessage(){
        System.out.println("YOU WON!!");
        System.out.println("Your wins: " + humanWinCount);
        System.out.println("Computer wins: " + computerWinCount);
        System.out.println("Ties: " + tieCount);
    }

    public void showComputerWinMessage(){
        System.out.println("YOU LOST!!");
        System.out.println("Your wins: " + humanWinCount);
        System.out.println("Computer wins: " + computerWinCount);
        System.out.println("Ties: " + tieCount);
    }

    public void showTieMessage(){
        System.out.println("Tie!!");
        System.out.println("Your wins: " + humanWinCount);
        System.out.println("Computer wins: " + computerWinCount);
        System.out.println("Ties: " + tieCount);
    }

    public void decideWinner(){
        if(humanWinCount > computerWinCount){
            System.out.println();
            System.out.println("Yippee!! You won the Game!!");
        }else if(computerWinCount > humanWinCount){
            System.out.println();
            System.out.println("Oops!! You lost the Game!!");
            System.out.println("Better Luck Next Time!!");
        }
    }

    public static void main(String[] args) {
        RockPepperScissor rps = new RockPepperScissor();
        rps.startGame();
        rps.decideWinner();
    }
}

我希望这对您的学习活动有所帮助。

【讨论】:

    【解决方案4】:

    所以很明显代码不是模块化的,代码中有多余的语句。它们可能仍然存在,因为我所做的只是修复逻辑并在代码上为引入的更改制作 cmets -

    public class Rock_Paper_Scissors {
    
        public static void main(String arg[]) {
            boolean loopGameStart = true;
            while (loopGameStart) {
                System.out.println(
                        "Welcome to Rock Paper Scissors, a game programmed by Daniel Park. Would you like to start? (Y/N)");
                Scanner userInput = new Scanner(System.in);
                String determination = userInput.next();
    
                switch (determination) {
                    case "N":
                        System.out.println("Please, do reconsider...");
                        loopGameStart = true; // you might not want the player to be trapped here, so change it to `false` rather
                        break;
                    case "Y":
                        /** 0 = Rock, 1 = Paper, 2 = Scissor */
                        int humanWinCount = 0;
                        int computerWinCount = 0;
    
                        System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
                        Scanner userRPS = new Scanner(System.in);
                        int userChoice = userRPS.nextInt();
    
                        while ((humanWinCount < 5) && (computerWinCount < 5)) { // either of them reaches 5
                            int computerChoice = new Random().nextInt(3); // this is fun, no more static computer choice
                            if (userChoice == computerChoice) { // break quick if its a tie
                                System.out.println("TIE!!");
                                displayStats(computerWinCount, humanWinCount);
                                askChoice();
                            } else {
                                switch (userChoice) { //based on userChoice and computerChoice combination
                                    case 0:
                                        if (computerChoice == 1) {
                                            System.out.println("LOSS!!");
                                            displayStats(computerWinCount++,
                                                    humanWinCount); // incrementing the computerCount as well
                                            askChoice();
                                        } else if (computerChoice == 2) {
                                            System.out.println("WIN!!");
                                            displayStats(computerWinCount,
                                                    humanWinCount++); // incrementing the humanCount as well
                                            askChoice();
                                        }
                                        break;
                                    case 1:
                                        if (computerChoice == 0) {
                                            System.out.println("WIN!!");
                                            displayStats(computerWinCount, humanWinCount++);
                                            askChoice();
                                        } else if (computerChoice == 2) {
                                            System.out.println("LOSS!!");
                                            displayStats(computerWinCount++, humanWinCount);
                                            askChoice();
                                        }
                                        break;
                                    case 2:
                                        if (computerChoice == 0) {
                                            System.out.println("LOSS");
                                            displayStats(computerWinCount++, humanWinCount);
                                            askChoice();
                                        } else if (computerChoice == 1) {
                                            System.out.println("WIN!!");
                                            displayStats(computerWinCount, humanWinCount++);
                                            askChoice();
                                        }
                                        break;
                                    default:
                                        System.out.println("I do not understand... Try again.");
                                        displayStats(computerWinCount, humanWinCount);
                                        askChoice();
                                        break;
    
                                }
                            }
    
                            userChoice = userRPS.nextInt(); //next iteration input only required once
                        }
    
                        if (humanWinCount == 5) {
                            System.out.println("Congratulations, you win!!");
                        } else {
                            System.out.println("Boohoo, you lost!!");
                        }
                        displayStats(computerWinCount, humanWinCount);
                        System.out.println("Would you like to try again? (Y/N)");
                        Scanner continueOrNot = new Scanner(System.in);
                        String contOrNot = continueOrNot.next();
                        if (contOrNot.equals("Y")) {
                            loopGameStart = true;
                        } else if (contOrNot.equals("N")) {
                            System.out.println("Okay, goodbye!!");
                            loopGameStart = false;
                        }
                        break;
    
    
                    default:
                        System.out.println("I do not understand, please try again!");
                        break;
                }
            }
        }
    
        private static void askChoice() {
            System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
        }
    
        private static void displayStats(int computerWinCount, int humanWinCount) {
            System.out.println("Computer: " + computerWinCount + " rounds won");
            System.out.println("You: " + humanWinCount + " rounds won");
        }
    }
    

    代码解释将是我将留在您不会理解的内容上的内容。因此,请进一步询问您可能想了解使用它的原因。

    【讨论】:

      【解决方案5】:

      如果您需要使用条件行为循环某些代码,请尝试使用递归参数方法并将条件部分代码分别封装到单独的方法中。这些方法将从当前递归中调用。然后从main方法调用第一次递归级别。

      伪样本:

      public int myRecursiveMethod_RPS (int aVariable)
      {
        System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
        ...
        // your own logic below - this is just sample
        if (aVariable == 0) 
          return myRecursiveMethod_RPS(0);
        else if (aVariable >= 0) 
          return myRecursiveMethod_RPS(aVariable);
        else return aVariable;
      }
      

      关于递归的好文章在这里Recursion - Java 或 这里https://howtoprogramwithjava.com/java-recursion/

      【讨论】:

        【解决方案6】:

        尝试使用 do/while 循环。代码一直运行到某个条件不再满足,但即使一开始条件不成立,它也至少会运行一次。以您的第一个输入为例,它看起来就像这样:

        String determination; // I move the variable determination outside so it is in the scope of the while.
        
        do {
        System.out.println(
                            "Welcome to Rock Paper Scissors, a game programmed by Daniel Park. Would you like to start? (Y/N)");
                    Scanner userInput = new Scanner(System.in);
                    determination = userInput.next();
        } while (determination != "Y" || determination != "N");
        //...
        

        代码至少会运行一次。如果在任何时候“确定”等于“N”或“Y”,它将继续执行其余代码。

        您可以从这个网站获得更多信息: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

        【讨论】:

          【解决方案7】:

          正如我已经编辑到您的程序的 addons_zz 模块化版本 Perambulation:如果您输入例如,用于用户输入的扫描仪抛出 InputMismatchException "a" 和 Scanner 的 nextInt() 方法被调用。输入“a”不能转换为整数类型,因为它是字母表中的一个字符。对此的解决方案可能如下所示(在您的代码版本中):

          ...
          } else if (determination.equals("Y")) {
              Random rand = new Random();
              int n = rand.nextInt(3) + 1;
              // 1 = Rock, 2 = Paper, 3= Scissor
              int humanWinCount = humanWinCount();
              int computerWinCount = computerWinCount();
              Scanner userRPS = new Scanner(System.in);
          
              // loop until choiceRPS is 0, 1 or 2
              int choiceRPS = 9;
              boolean choiceRPSNotSet = true;
              while(choiceRPSNotSet){
          
                  System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
          
                  try
                  {
                      choiceRPS = userRPS.nextInt();
          
                      if( choiceRPS >= 0 && choiceRPS <= 2 )
                      {
                          choiceRPSNotSet = false;
                      }
                  }
                  catch( InputMismatchException e )
                  {
                      System.out.println( "I do not understand, please try again!" );
                      userRPS.next();
                  } 
              }
              // loop until choiceRPS is 0, 1 or 2
          
              while ((humanWinCount < 5) && (computerWinCount < 5)) {
              ...
          

          所以我根据choiceRPS设置正确的条件添加了另一个while循环。

          if( choiceRPS >= 0 && choiceRPS <= 2 )
                  {
                      choiceRPSNotSet = false;
                  }
          

          只有这样才会留下包含捕获异常的循环,因为这部分位于 try/catch 块中。

          如果发生 InputMismatchException,则调用 userRPS.next()(或 Scanner.next())方法将从 Scanner 中清除 Input,以便读取新的输入。

          我推荐的另一种方法是将用户输入封装到自己的方法中,例如:

          public static int choose(){
              Scanner userRPS = new Scanner(System.in);
              // loop until choiceRPS is 0, 1 or 2
              int choiceRPS = 9;
              boolean choiceRPSNotSet = true;
              while(choiceRPSNotSet){
          
                  System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
          
                  try
                  {
                      choiceRPS = userRPS.nextInt();
          
                      if( choiceRPS >= 0 && choiceRPS <= 2 )
                      {
                          choiceRPSNotSet = false;
                      }
                  }
                  catch( InputMismatchException e )
                  {
                      System.out.println( "I do not understand, please try again!" );
                      userRPS.next();
                  } 
              }
              // loop until choiceRPS is 0, 1 or 2
              return choiceRPS;
          }
          

          并在必要时调用此 choose() 方法,例如:

          ...
          } else if (determination.equals("Y")) {
                  Random rand = new Random();
                  int n = rand.nextInt(3) + 1;
                  // 1 = Rock, 2 = Paper, 3= Scissor
                  int humanWinCount = humanWinCount();
                  int computerWinCount = computerWinCount();
          
          
                  int choiceRPS = choose();
          
              while ((humanWinCount < 5) && (computerWinCount < 5)) {
                if (choiceRPS == 0) {
                  if (n == 1) {
                    System.out.println("TIE!!");
                    System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                    System.out.println("Computer: " + computerWinCount + " rounds won");
                    System.out.println("You: " + humanWinCount + " rounds won");
          
                    choiceRPS = choose();
          
                  } else if (n == 2) {
                    System.out.println("LOSS!!");
                    System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                    computerWinCount = computerWinCount + 1;
                    System.out.println("Computer: " + computerWinCount + " rounds won");
                    System.out.println("You: " + humanWinCount + " rounds won");
          
                    choiceRPS = choose();
          ...
          

          希望这会有所帮助! ^^

          【讨论】:

            【解决方案8】:
            import java.util.*;
            
            public class Rock_Paper_Scissors {
            
              public static void main(String arg[]) {
                boolean loopGameStart = true;
            
                while (loopGameStart) {
                  System.out.println("Welcome to Rock Paper Scissors, a game programmed "
                                   + "by Daniel Park. Would you like to start? (Y/N)");
                  Scanner userInput = new Scanner(System.in);
                  String determination = userInput.next();
                  //1=THIS CHANGED TO IGNORE CASE N or n Y or y accepted
                  if (determination.equalsIgnoreCase("N")) {
                    System.out.println("Please, do reconsider...");
                    loopGameStart = true;
                  } else if (determination.equals("Y")) {
                    Random rand = new Random();
                    int n = rand.nextInt(3) + 1;
                    // 1 = Rock, 2 = Paper, 3= Scissor
                    int humanWinCount = humanWinCount();
                    int computerWinCount = computerWinCount();
                    System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
                    Scanner userRPS = new Scanner(System.in);
                    int choiceRPS = userRPS.nextInt();
                    while ((humanWinCount < 5) && (computerWinCount < 5)) {
                      if (choiceRPS == 0) {
                        if (n == 1) {
                          System.out.println("TIE!!");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        } else if (n == 2) {
                          System.out.println("LOSS!!");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          computerWinCount = computerWinCount + 1;
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        } else if (n == 3) {
                          System.out.println("WIN!!");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          humanWinCount = humanWinCount + 1;
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        } else {
                          System.out.println("I do not understand... Try Again.");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        }
                      } else if (choiceRPS == 1) {
                        if (n == 1) {
                          System.out.println("WIN!!");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          humanWinCount = humanWinCount + 1;
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        } else if (n == 2) {
                          System.out.println("TIE!!");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        } else if (n == 3) {
                          System.out.println("LOSS!!");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          computerWinCount = computerWinCount + 1;
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        } else {
                          System.out.println("I do not understand... Try again.");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        }
                      } else if (choiceRPS == 2) {
                        if (n == 1) {
                          System.out.println("LOSS");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          computerWinCount = computerWinCount + 1;
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        } else if (n == 2) {
                          System.out.println("WIN!!");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          humanWinCount = humanWinCount + 1;
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        } else if (n == 3) {
                          System.out.println("TIE!!");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        } else {
                          System.out.println("I do not understand... Try again.");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                        }
                      }else{
                          //###################################THIS IS THE ADDED CODE
                          System.out.println("INVALID VALUE ENTER AGAIN");
                          System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
                          System.out.println("Computer: " + computerWinCount + " rounds won");
                          System.out.println("You: " + humanWinCount + " rounds won");
                          choiceRPS = userRPS.nextInt();
                      }
                    }
            
                    if (humanWinCount == 5) {
                      System.out.println("Congratulations, you win!!");
                      System.out.println("Computer: " + computerWinCount + " rounds won");
                      System.out.println("You: " + humanWinCount + " rounds won");
                      System.out.println("Would you like to try again? (Y/N)");
                      Scanner continueOrNot = new Scanner(System.in);
                      String contOrNot = continueOrNot.next();
                      if (contOrNot.equals("Y")) {
                        loopGameStart = true;
                      } else if (contOrNot.equals("N")) {
                        System.out.println("Okay, goodbye!!");
                        loopGameStart = false;
                      }
                    }
            
                    if (computerWinCount == 5) {
                      System.out.println("Boohoo, you lost!!");
                      System.out.println("Computer: " + computerWinCount + " rounds won");
                      System.out.println("You: " + humanWinCount + " rounds won");
                      System.out.println("Would you like to try again? (Y/N)");
                      Scanner continueOrNot = new Scanner(System.in);
                      String contOrNot = continueOrNot.next();
                      if (contOrNot.equals("Y")) {
                        loopGameStart = true;
                      } else if (contOrNot.equals("N")) {
                        System.out.println("Okay, goodbye!!");
                        loopGameStart = false;
                      }
                    }
                  } else {
                    System.out.println("I do not understand, please try again!");
                  }
                }
            
            
                }
                  public static int humanWinCount() {
                      int x = 0;
                      return x;
                  }
            
                  public static int computerWinCount() {
                      int c = 0;
                      return c;
                  }
                }
            

            【讨论】:

              【解决方案9】:

              只需一个简单的循环就可以解决问题:

              Scanner answerScanner = new Scanner(System.in);
              do{
                char answer = answerScanner.next().charAt(0);
              }while(answer != 'Y' && answer != 'N');
              
              // Then do whatever you need to do
              if(answer == 'Y'){
                // Something
              }else{
                // Something else
              }
              

              请注意,如果您想允许“y”和“n”作为答案,可以使用 answerScanner.next().toUpperCase().charAt(0)。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2020-08-03
                • 1970-01-01
                • 1970-01-01
                • 2021-07-16
                • 1970-01-01
                • 2016-01-14
                • 1970-01-01
                相关资源
                最近更新 更多