Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop a certain area of code after a wrong user input? (Java)

Tags:

java

I have been working on a small Rock Paper Scissors game with Java, where the win or lose condition is based on whether the computer or the player wins five games. I am not sure how to get the program to loop at the user input should there be a wrong input.

Here is the code where I'm having this trouble

The section that I'm trying to loop is the portion with "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;
  }
}
like image 913
Perambulation Avatar asked Dec 03 '16 01:12

Perambulation


3 Answers

Please, do not write everything in one main function, or repeat the same code everywhere, and etc.

I completely rebuild your code and also implemented the loop @Austin suggested. Now your should be working as you which or very close. Enjoy:

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" );
    }
}
like image 143
user Avatar answered Oct 21 '22 02:10

user


You can use a do while

int choiceRPS;
 do{
    choiceRPS = userRPS.nextInt();
}while(choiceRPS<0||choiceRPS>2);
like image 7
Austin Avatar answered Oct 21 '22 03:10

Austin


Your logic looks very complex. It can be easily simplified as the game has only 3 outcomes other that a tie.

SCISSORS beats PAPER

PAPER beats ROCK

ROCK beats SCISSORS

So considering the inputs as 0, 1 and 2 representing Rock, Paper and Scissors respectively:

  1. You need to keep track of two numbers. One is user entered choice let's call it userChoice and another being computerChoice which is computer's played choice. This computerChoice should be a randomly chosen digit between 0 and 2 both inclusive.
  2. Now, start comparing both the numbers to decide on the winner and increment the respective counter (humanWinCount and computerWinCount).
  3. Stop the game and decide the winner when either the user or the computer wins at least 5 rounds.

Hence, your gaming loop should be looking something like this:

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;
            }
        }

And the entire remodeled code should be looking something like this:

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();
    }
}

I hope this helps you in your learning activity.

like image 5
Shyam Baitmangalkar Avatar answered Oct 21 '22 01:10

Shyam Baitmangalkar