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();
    }
}
Tom
  • 14,120
  • 16
  • 41
  • 47
Bhagyesh
  • 576
  • 6
  • 21
  • 2
    `Main.main(args); // Exit program` Please rethink that. – Tom Oct 18 '15 at 17:01
  • 1
    Possible duplicate of [How to read integer value from the standard input in Java](http://stackoverflow.com/questions/2506077/how-to-read-integer-value-from-the-standard-input-in-java) – BackSlash Oct 18 '15 at 17:01
  • Duplicate of [How do i make an if statement have multiple strings?]( https://stackoverflow.com/questions/33199575/how-do-i-make-an-if-statement-have-multiple-strings) from same user using different algorhytm, despite getting correct answers – The Law Oct 18 '15 at 17:07

3 Answers3

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.

ataulm
  • 14,077
  • 7
  • 44
  • 90
  • 2
    Interessting approach, but I wouldn't rely on `ordinal` and would create an `int` field in that enum and define the numbers myself. – Tom Oct 18 '15 at 17:19
  • 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. – ataulm Oct 18 '15 at 17:38
  • 1
    Yes they can be compared, but OP used a randomly generated _number_ for the computer :P. – Tom Oct 18 '15 at 17:41
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

SkyvrawleR
  • 312
  • 2
  • 5
  • 17
Suresh Atta
  • 114,879
  • 36
  • 179
  • 284
  • 2
    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? – Tom Oct 18 '15 at 17:03
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();
Community
  • 1
  • 1
Fundhor
  • 2,729
  • 1
  • 20
  • 41
  • 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 – Fundhor Oct 18 '15 at 17:06
  • 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. – BackSlash Oct 18 '15 at 17:10
  • 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. – Fundhor Oct 18 '15 at 17:29