0

How can I compare a string with an int? I am making a Rock-paper-scissors game and how do I turn the string the user enters in to a int so the program can check who had won? Such as if the users enters "rock" the program registers that as 0 and so on?

package rpc;

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

public class Main {
    public static void main(String[] args) {
        /* Random number generator */
        Random random = new Random();

        /* Scanner object for input */
        Scanner scanner = new Scanner(System.in);

        /*
         * Integer variables to hold the user and computer choice.
         * 0 = Rock
         * 1 = Paper
         * 2 = Scissors
         */
        String userChoice;
        int computerChoice;

        // Showing prompt and user input
        System.out.println("Enter move (0 = Rock; 1 = Paper; 2 = Scissors):");
        userChoice = scanner.nextLine();

        // Checking if userChoice is 0, 1, or 2.
        if (!userChoice.equalsIgnoreCase("Scissors") && !userChoice.equalsIgnoreCase("Paper")
            && !userChoice.equalsIgnoreCase("rock")) {
            System.out.println("Invalid choice. Ending program.");

            // Exit program
            Main.main(args);
        }

        // Generating random computer choice
        computerChoice = random.nextInt(3);

        // Determining the winner

        // If the choices are equal, it's a tie.
        if (userChoice == computerChoice) {
            if (userChoice == 0) {
                System.out.println("Both players chose rock!");
            } else if (userChoice == 1) {
                System.out.println("Both players chose paper!");
            } else {
                System.out.println("Both players chose scissors!");
            }

            // Exit program
            System.exit(0);
        }

        if (userChoice == 0) {        // User chooses rock
            if (computerChoice == 1) {
                System.out.println("You chose rock; Computer chose paper");
                System.out.println("Computer wins!");
            } else {
                System.out.println("You chose rock; Computer chose scissors");
                System.out.println("You win!");
            }
        } else if (userChoice == 1) {    // User chooses paper
            if (computerChoice == 0) {
                System.out.println("You chose paper; Computer chose rock");
                System.out.println("You win!");
            } else {
                System.out.println("You chose paper; Computer chose scissors");
                System.out.println("Computer wins!");
            }
        } else {    // User chooses scissors
            if (computerChoice == 0) {
                System.out.println("You chose scissors; Computer chose rock");
                System.out.println("Computer wins!");
            } else {
                System.out.println("You chose scissors; Computer chose paper");
                System.out.println("You win!");
            }
        }
        scanner.close();
    }
}
3

3 Answers 3

2

You could use an enum to enumerate the three possible choices:

enum Hand {

    ROCK,
    PAPER,
    SCISSORS;

    public static Hand from(String input) {
        for (Hand hand : values()) {
            if (hand.name().equalsIgnoreCase(input)) {
                return hand;
            }
        }
        throw new IllegalArgumentException("Invalid choice: " + input);
    }

}

Enums have an intrinsic integer value (that corresponds to the position they were defined at). ROCK.ordinal() will return 0, for example.

Sign up to request clarification or add additional context in comments.

3 Comments

Interessting approach, but I wouldn't rely on ordinal and would create an int field in that enum and define the numbers myself.
Depends on how/what the ordinal is used for. In this case, I guess the number/ordinal isn't required anyway - the enums can be compared against each other.
Yes they can be compared, but OP used a randomly generated number for the computer :P.
0

Just use pareseInt and convert string to int

For ex :

if(Integer.parseInt(userChoice) == computerChoice)

Make sure that the inputs are not null and formattable to int

edit : change parese to parse

1 Comment

Have you noticed the if which contains checks like !userChoice.equalsIgnoreCase("Scissors")? So we already know, that the user enters a String/word ... how should he parse that to an int?
0

Retrieving a random item from ArrayList

This is not the exact answer to your question (Integer.parseInt(myInt)) but you could try something more readable like this, avoiding the use of unnecessary Integers. And simplifies your code

Generate your arrayList and then pick the random "computer" choice.

List<String> posibilities = Arrays.asList("rock","paper","scissors");
String computerChoice = possibilites.get(Math.random(3));

then do your comparaison ;)

/* Chose the possibilities */
List<String> posibilities = Arrays.asList("rock","paper","scissors");

/* Scanner object for input */
Scanner scanner = new Scanner(System.in);

// Showing prompt and user input
System.out.println("Enter move (0 = Rock; 1 = Paper; 2 = Scissors):");
String userChoice = scanner.nextLine();
userChoice = possibilities.get(Integer.parseInt(userChoice));

// Checking if userChoice is 0, 1, or 2.
if(!possibilities.contains(userChoice)) {
    System.out.println("Invalid choice. Ending program.");

    // Exit program
    Main.main(args);
}

// Generating random computer choice
String computerChoice = possibilites.get(Math.random(3));

// Determining the winner

// If the choices are equal, it's a tie.
if(userChoice.equals(computerChoice)) {
    System.out.println("Both players chose " + userChoice);

    // Exit program
    System.exit(0);
}

System.out.println("You chose " + userChoice + "; Computer chose " + computerChoice);
if(userChoice.equals("rock")) {    // User chooses rock
    if(computerChoice.equals("paper")) {
            System.out.println("Computer wins!");
    } else {
        System.out.println("You win!");
    }
}
else if(userChoice.equals("paper")) {  // User chooses paper
    if(computerChoice.equals("rock")) {
        System.out.println("You win!");
    } else {
        System.out.println("Computer wins!");
    }
} else {   // User chooses scissors
    if(computerChoice.equals("Scissors")) {
        System.out.println("Computer wins!");
    } else {
        System.out.println("You win!");
    }
}

scanner.close();

3 Comments

Well, yes, but the code will be more readable comparaing directly String, instead of going through a whole process transforming them into int. Avoiding the use of unnecessary comments
The OP didn't ask how to make the computer pick a random number, he asked how to convert a string to an int. Your answer doesn't really make sense. Re-read the question.
I added the correct answer, since it might be useful for him another time. But I maintain that other possibilites offer much more readable code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.