如何在错误的用户输入后循环某个代码区域?(JAVA)

Per*_*ion 18 java

我一直在研究一款带有Java的小型Rock Paper Scissors游戏,其中输赢的条件取决于计算机或玩家是否赢得五场比赛.如果输入错误,我不知道如何让程序循环用户输入.

这是我遇到麻烦的代码

我试图循环的部分是"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;
  }
}
Run Code Online (Sandbox Code Playgroud)

use*_*ser 13

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

我完全重建了你的代码,并实现了@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" );
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然你很高兴重写整个程序,但我不认为这是stackoverflow的目标.我不认为,Perambulation会学到很多这样的答案...... (5认同)

Aus*_*tin 7

你可以使用do while

int choiceRPS;
 do{
    choiceRPS = userRPS.nextInt();
}while(choiceRPS<0||choiceRPS>2);
Run Code Online (Sandbox Code Playgroud)


小智 5

你的逻辑看起来很复杂.它可以很容易地简化,因为游戏只有3个结果,而不是平局.

剪刀击败纸张

PAPER击败ROCK

ROCK击败了剪刀

因此,考虑输入为0,1和2分别代表Rock,Paper和Scissors:

  1. 你需要跟踪两个数字.一个是用户输入的选择让我们调用它userChoice而另一个computerChoice是计算机的选择.这computerChoice应该是0到2之间随机选择的数字,包括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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

并且整个重新构建的代码应该看起来像这样:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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