1

I am writing a rock paper scissors game in java but there are some things I can't figure out. First of all, I want to make it so that the user can type "Rock" or "paper" instead of 1, 2, and 3 but I can't figure that out. Secondly, I'm supposed to be using nested if else statements but I don't know how to do that either with what I've been doing. My code is below

import java.util.Scanner; public class RockGame {

  private final static int ROCK=1;
  private final static int PAPER =2;
  private final static int SCISSOR =3;

  private static Scanner key;




public static void main(String args[]){
         int playerOneScore = 0;
         int computerScore = 0;

         int userPlay, computerPlay;


        String val = key.nextLine().toLowerCase();

         key = new Scanner(System.in);
         while(playerOneScore <2 && computerScore <2){


                 System.out.println("Choose 1 for rock, 2 for paper, and 3 for sciscors!");
                 userPlay = key.nextInt();
                 computerPlay = (int)(Math.random()*3) +1;
                 if(val.equals("rock"))
                       userPlay = ROCK;

                 else if (val.equals("paper"))
                         userPlay =PAPER;

                 else if (val.equals("scissors"))
                         userPlay=SCISSOR;


                 if (val.equals("rock"))
                         computerPlay = ROCK;
                 else if (val.equals("paper"))
                         computerPlay =PAPER;
                 else if (val.equals("scissors"))
                         computerPlay=SCISSOR;

                 if (computerPlay ==ROCK && userPlay==SCISSOR ){
                         System.out.println("The computer chose rock, you chose scissors.\n You lose!");
                         computerScore++;
                 }
                 if (computerPlay ==ROCK && userPlay==PAPER ){
                         System.out.println("You computer chose rock, you chose paper.\n You win!");
                         playerOneScore++;
                 }
                 if (computerPlay ==PAPER && userPlay==SCISSOR ){
                        System.out.println("The computer chose scissors, you chose paper.\n You win!");
                         playerOneScore++;
                 }
                 if (computerPlay ==PAPER && userPlay==ROCK ){
                         System.out.println("The computer chose paper and you chose rock. \n You lose!");
                         computerScore++;
                 }
                 if (computerPlay ==SCISSOR && userPlay==ROCK ){
                         System.out.println("The computer chose scissors and you chose rock. \n You win!");
                         playerOneScore++;
                 }
                 if (computerPlay ==SCISSOR && userPlay==PAPER ){
                         System.out.println("The computer chose scissors and you chose paper. \n You lose!");
                         computerScore++;
                 }
                 if (computerPlay == userPlay ){
                         System.out.println("The computer chose the same thing you did! \n Tie!");

                 }


         }
         if(computerScore > playerOneScore)
                 System.out.println("Computer win score is: - "+ computerScore + " -" + playerOneScore  );
         else
                 System.out.println("Your score is: " + playerOneScore + "-" + computerScore );


  }


}
user2792922
  • 11
  • 1
  • 3
  • If you want the user to type in a string, then use strings rather than integers. The answer below explains how to do that. – user2202911 Sep 19 '13 at 01:29
  • You use `key.nextInt()`, so you have to enter numbers. If you use `key.next()` you would be able to enter strings. You should use `else if` constructs in your "computer vs user" logic, since all pairs are mutually exclusive. – PM 77-1 Sep 19 '13 at 01:32

10 Answers10

4

I want to make it so that the user can type "Rock" or "paper" instead of 1, 2, and 3

Use key.nextLine().toLower(), then test whether this value equals "rock", etc.

I'm supposed to be using nested if else statements

Notice in your code:

if (computerPlay ==SCISSOR && userPlay==ROCK ){
    // etc.
}
if (computerPlay ==SCISSOR && userPlay==PAPER ){
    // etc.
}

You check whether computerPlay == SCISSOR twice. Whereas with a nested statement you can do something more like:

if (computerPlay == SCISSOR) {
    if (userPlay == ROCK) {
        // etc.
    else if (userPlay == PAPER) {
        // etc.
    }
}
William Gaul
  • 3,181
  • 2
  • 15
  • 21
  • You've been very helpful, but for whatever reason my code won't work now. I know I'm probably an idiot, but can you see the problem? I edited the code to reflect what I now have. – user2792922 Sep 19 '13 at 01:43
  • You use `key` before declaring it (initializing the Scanner). So move the line that says `String val = key.nextLine().toLowerCase();` down to below `key = new Scanner(System.in);`. – William Gaul Sep 19 '13 at 01:52
2

Use:

string val = sc.nextLine().toLower();

And then:

if(val.equals("rock") {
   userPlay = ROCK;
}
else if(...) {
   //..
}

You can use nested if-loops like:

if(userPlay == ROCK) {
  if(computerPlay == ROCK) {
    System.out.println("The computer chose the same thing you did! \n Tie!");
  }
  else if(computerPlay == PAPER) {
    System.out.println("The computer chose paper and you chose rock. \n You lose!");
    computerScore++;
  }
  else {
    System.out.println("The computer chose scissors and you chose rock. \n You win!");
    playerOneScore++;
  }
}
else if(userPlay == PAPER) {
  if(computerPlay == ROCK) {
    System.out.println("You computer chose rock, you chose paper.\n You win!");
    playerOneScore++;
  }
  else if(computerPlay == PAPER) {
    System.out.println("The computer chose the same thing you did! \n Tie!");
  }
  else {
    System.out.println("The computer chose scissors and you chose paper. \n You lose!");
    computerScore++;
  }
}
//I think you get the idea...
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • I'm sorry I'm really new, what does the first line do? – user2792922 Sep 19 '13 at 01:29
  • It reads a line from the command line... And stores it into the `val` string (of course you can use another variable name if you like). You don't have to be sorry, we all started at this level... Although I have to say looking back the code doesn't look elegant. But no offense :D) – Willem Van Onsem Sep 19 '13 at 01:31
  • 2
    Nice new type of loop, if-loops! :) – Diego C Nascimento Sep 19 '13 at 01:39
  • And `toLower` will convert the string to lower characters. So `"RoCk"` becomes `"rock"`. – Willem Van Onsem Sep 19 '13 at 01:40
  • @Diego C Nascimento: in Dutch some books state "if-lussen". A literal translations means "if-loops". Furthermore it's not that uncommon: https://www.google.be/search?&q=%22if+loop%22 – Willem Van Onsem Sep 19 '13 at 01:41
  • Yeah but ironically enough, a "lus" in Dutch also means repetition (and not "block"). At first I was annoyed with the word "if lus", but after a while, one starts using that... :( – Willem Van Onsem Sep 19 '13 at 01:48
1

Try this

        // paper == 0
        // rock == 1
        // scissors == 2
        System.out.println("Select 0 for Paper \nSelect 1 for Rock \nSelect 2 for Scissors");
        Scanner scan = new Scanner(System.in);
        int player = scan.nextInt();
        Random comp = new Random();
        int com = comp.nextInt(2);
        System.out.println(com);
        if (player == com){
            System.out.println("Match is Tie");
        }else{
            switch (com){
                case 0:
                    if(player == 2){
                        System.out.println("Player Wins the Match");
                    }else{
                        System.out.println("Comp wins the Match");
                    }
                    break;
                case 1:
                    if(player == 0){
                        System.out.println("Player Wins the Match");
                    }else{
                        System.out.println("Comp wins the Match");
                    }
                    break;
                case 2:
                    if(player == 1){
                        System.out.println("Player Wins the Match");
                    }else{
                        System.out.println("Comp wins the Match");
                    }
                    break;
            }
        }
0

First, you'll want to create an enum, and then parse the user's input into that enum:

Lookup enum by string value

As for nested if-else statements, technically

if(something){
    // do something
}else if(somethingElse){
    // do something else
}else{
    // do another things
}

is a nested if-else statement. At least that's how it looks to the compiler.

I suspect your teacher wants to see a structure like:

if(computerPlay == ROCK){
    if(userPlay == PAPER){
    }
    else if(userPlay == ROCK){
    }
    else if(userPlay == SCISSOR){
    }
}
else if(computerPlay == PAPER){
    // same as above
}
else if(computerPlay == SCISSOR){
    // same as above
}
Community
  • 1
  • 1
Jestin
  • 330
  • 2
  • 13
0

First, you don't need these lines:

if (computerPlay==1)
    computerPlay = ROCK;
if (computerPlay==2)
    computerPlay =PAPER;
if (computerPlay==3)
    computerPlay=SCISSOR;

Second, you say you are supposed to use nested if/else statements - perhaps this is what your teacher is after:

if (computerPlay == ROCK)
{
    if (userPlay==ROCK)
    {
        ...
    }
    else if (userPlay == PAPER)
    {
        ...
    }
    else if (userPlay == SCISSORS)
    {
        ...
    }
    else
    {
        // Cheating!
    }
}
else if (computerPlay == PAPER)
{
    if (userPlay==ROCK)
    {
        ...
    }
    // And so on...

That's a very long-winded way of doing things (I'd personally do a two-dimensional array look-up) and your original code looks acceptable, but it's a learning exercise, I guess, to get you used to nested if/elses.

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
0

You could use .equalsIgnoreCase(); to check for "Rock","Paper","etc" or it will even match if the user inputs "rock", "PaPER",etc. Also adding in nested if statements will make your function much more efficient. To make a nested if statement, all that you need to do is place one if statement within another like shown below.

    if(userPlay.equalsIgnoreCase("Rock")) {

         if (computerPlay.equalsIgnoreCase("Scissors"){
                System.out.println("The computer chose scissors, you chose rock.\n You win!");
                             playerOneScore++;
         }
         else if (computerPlay.equalsIgnoreCase("Paper")){
                System.out.println("You computer chose paper, you chose rock.\n You lose!");
                             computerScore--;
         }
     }

With these nested if statements you will only need to check the users choice once per option instead of multiple times like in your example code.

You will also need to change from key.nextInt() to key.next() so that you are taking strings as inputs and storing them in userPlay instead of integers

userPlay = key.next();

Hope that is of some use to you!

Bryan
  • 1,938
  • 13
  • 12
0

After some thought this is what you could do,

Create an enum with elements

enum Elements{ROCK ,PAPER ,SCISSORS};

Create a second enum for the various combinations of the Elements, and also implementing an interface,

enum ElementCombinations implements RockPaperScissorssLogic
{
    ROCK_PAPER
    {
        int decideWinner()
        {
            //For second player
            return 2;
        }
    }, 
    PAPER_SCISSORS
    {
        int decideWinner()
        {
            //For second player
            return 2;
        }
    }, 
    ..... ;

    // For obtaining decide the type of combination object to be used.
    public static ElementCombinations getCombination(Element player1, Element player2)
    {
        // Some logic...
    }
};

Finally in your code you coud simply call the decide winner method of the ElementCombinations object to get the winning player.

R.daneel.olivaw
  • 2,681
  • 21
  • 31
0

In my personal option, all given answers over-complicates things.

Here is a very simple example by storing a simple 2-d array.

public class Main{

   public final static int SCISSORS = 0;
   public final static int PAPER = 1;
   public final static int STONE = 2;

   public static void rockPaperScissors(int player1, int player2){
        if(player1 == player2){ System.out.println("Tie"); return;}

        boolean key[][] = {
             {false, true, false},
             {false, false, true},
             {true, false, false} 
        };

        boolean player1Wins = key[player1][player2];

        if(player1Wins){ System.out.println("Player one wins"); }
        else{ System.out.println("Player two wins"); } 

   }

  public static void main(String[] arrgs){

       rockPaperScissors(SCISSORS, STONE);
 }

}

The array stores all possible results.

0
import java.util.Scanner;

public class RockPaperScissors {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Hey let's play Rock, Paper, Scissors!");
System.out.println("You must choose 1 for Rock, 2 for Paper and 3 for Scissors");
System.out.print("Rock, Paper or Scissors? ");
int play = console.nextInt();
String user = intToName(play,console);
int person = play;
int computer = generateRandomNumber(1,3);

}
    public static String intToName(int play,Scanner console){
    String choose = "";
     if (play == -1){
         System.out.print("Game Over!");
     }
    while (play != -1){
    if (play == 1){
        System.out.println("Your play is: Rock");
         if (generateRandomNumber(1,3) == 1){
                System.out.println("Computer player is: Rock");  
                System.out.println("It's a tie!");
              }
         else if (generateRandomNumber(1,3) == 2){
                    System.out.println("Computer player is: Paper"); 
                    System.out.println("Paper eats Rock. You lose!");
              }
           else if (generateRandomNumber(1,3) == 3){
                    System.out.println("Computer player is: Scissors"); 
                    System.out.println("Rock eats Scissors. You win!");
              }
    }
    else if (play == 2){
        System.out.println("Your play is: Paper");
         if (generateRandomNumber(1,3) == 1){
                System.out.println("Computer player is: Rock");  
                System.out.println("Paper eats Rock. You win!");
              }
         else if (generateRandomNumber(1,3) == 2){
                    System.out.println("Computer player is: Paper");  
                    System.out.println("It's a tie!");
              }
         else  if (generateRandomNumber(1,3) == 3){
                    System.out.println("Computer player is: Scissors"); 
                    System.out.println("Scissors eats Paper. You lose!");
              }
    }
    else if (play == 3){
     System.out.println("Your play is: Scissors");
     if (generateRandomNumber(1,3) == 1){
            System.out.println("Computer player is: Rock"); 
            System.out.println("Rock eats Scissors. You lose!");
          }
     else if (generateRandomNumber(1,3) == 2){
                System.out.println("Computer player is: Paper");  
                System.out.println("Scissors eats Paper. You win!");
          }
     else if (generateRandomNumber(1,3) == 3){
                System.out.println("Computer player is: Scissors");  
                System.out.println("It's a tie!");
          }
    }
    System.out.println();
    System.out.print("Rock, Paper or Scissors? ");
   play = console.nextInt();
  }
    return choose;
    }
    public static int generateRandomNumber(int a, int b){
        return a+(int)(Math.random()*b-a+1);
    }
    public static int winner(int person, int computer){
        int win =0;
        int lose =0;
        int tie=0;
        if (person == 1 && computer == 1){
            tie++;
        }
        if (person == 2 && computer == 2){
            tie++;
        }
        if (person == 3 && computer == 3){
            tie++;
        }
        if (person == 1 && computer == 2){
             lose++;
        }
        if (person == 1 && computer == 3){
            win++;
        }
        if (person == 2 && computer == 1){
            win++;
        }
            if (person == 2 && computer == 3){
                lose++;
    }
            if (person == 3 && computer == 1){
                lose++;
            }
            if (person == 3 && computer == 2){
                win++;
            }
            return win;
    }
}
amk
  • 70
  • 7
0

public class RPS {

//userPlayer value must be:
//ROCK = 1
//PAPER = 2
//SCISSORS = 3
private int userPlayer;

int computerPlayer(){
    Random rand = new Random();
    return rand.nextInt(3) + 1;

}

String result(){

    int calculate=userPlayer-computerPlayer();
        if(calculate==0)
            return "tie";
        else if((calculate==1 ||calculate==-2))
            return "win";
        else
            return "loose";
}

void setUserPlayer(int value){
    userPlayer=value;
}

}

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 30 '22 at 14:43