so when I run my code, it keeps saying that it is a tie because I think there is a problem in one of my methods.
Here is my whole code:
String userChoice = "";
String computerChoice = "";
System.out.println("Welcome to Rock, Paper, Scissors.");
System.out.println("The rules of the game are Rock breaks Scissors, "
+ "Scissors cut Paper, and Paper covers Rock. In this game, "
+ "the user will play against the computer.");
System.out.println("The legend for this game is: R = rock, P = paper,"
+ " and S = scissors.");
generateUserChoice();
generateComputerChoice();
determiningOutcome(userChoice, computerChoice);
repeatGame(userChoice, computerChoice);
}
public static String generateComputerChoice() {
String computerChoice = "";
int computerIntChoice;
Random generator = new Random();
computerIntChoice = generator.nextInt(3) + 1;
if (computerIntChoice == 1) {
computerChoice = "R";
} else if (computerIntChoice == 2) {
computerChoice = "P";
} else if (computerIntChoice == 3) {
computerChoice = "S";
}
System.out.println("The computer played " + computerChoice);
return computerChoice;
}
public static String generateUserChoice() {
String userChoice;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter your choice:");
userChoice = input.nextLine();
userChoice = userChoice.toUpperCase();
return userChoice;
}
public static void determiningOutcome(String userChoice, String computerChoice) {
if (userChoice.equals(computerChoice)) {
System.out.println("It is a tie!");
} else if (userChoice.equalsIgnoreCase("R") && computerChoice.equalsIgnoreCase("S")) {
System.out.println("Rock beats Scissors, you win!!");
} else if (userChoice.equalsIgnoreCase("P") && computerChoice.equalsIgnoreCase("R")) {
System.out.println("Paper beats Rock, you win!!");
} else if (userChoice.equalsIgnoreCase("S") && computerChoice.equalsIgnoreCase("P")) {
System.out.println("Scissors beats Paper, you win!!");
} else if (computerChoice.equalsIgnoreCase("R") && userChoice.equalsIgnoreCase("S")) {
System.out.println("Rock beats Scissors, you lose.");
} else if (computerChoice.equalsIgnoreCase("P") && userChoice.equalsIgnoreCase("R")) {
System.out.println("Paper beats Rock, you lose.");
} else if (computerChoice.equalsIgnoreCase("S") && userChoice.equalsIgnoreCase("P")) {
System.out.println("Scissors beats Paper, you lose.");
} else {
System.out.println("Sorry, invalid choice.");
}
}
public static int repeatGame(String userChoice, String computerChoice) {
int playAgain;
Scanner input = new Scanner(System.in);
System.out.println("Would you like to play again? 1 = yes and 2 = no");
playAgain = input.nextInt();
if (playAgain == 1) {
System.out.println("Would you like to play again? 1 = yes and 2 = no");
generateUserChoice();
generateComputerChoice();
determiningOutcome(userChoice, computerChoice);
}else {
System.out.println("Thank you for playing!!");
}
return playAgain;
}
}
however I think the problem is in the generateComputerChoice part of my code
Thanks in advance
The problem is that the userChoice and computerChoice is always been empty therefore it always a tie.
You need to assign your userChoice and computerChoice from the return value of the methods.
like this:
userChoice = generateUserChoice();
computerChoice = generateComputerChoice();
Related
I have this while loop of a Rock Paper Scissors game and I have if/else if statements that tell you which player won, but the while loop is skipping it and going straight to the end of the loop where it asks if you want to play another game. How would I be able to change this?
Scanner scan = new Scanner(System.in);
String play = "";
System.out.print("Please enter Play if you want to play the game or anything else to Stop");
play = scan.nextLine();
while (play.equalsIgnoreCase("play")) {
System.out.println("Game " + gameCount + " Rock, Paper, Scissors - Play!");
System.out.print("Choose your weapon [R]ock, [P]aper, or [S]cissors: ");
String rps = scan.nextLine();
while (rps.equals('R') || rps.equals('P') || rps.equals('S')) {
System.out.println("You chose: " + rps);
}
int rand = (int)(Math.random() * 3);
String myMove = "";
if(rand == 0) {
myMove = "Rock";
}
else if(rand == 1) {
myMove = "Paper";
}
else {
myMove = "Scissors";
}
System.out.println("I chose: " + myMove);
if(rps.equals(myMove)) {
System.out.println("Tie!");
tieCount++;
}
else if(rps.equals('P') && myMove.equals("Scissors")) {
System.out.println("Scissors beats paper, a win for me!");
myCount++;
}
else if(rps.equals('S') && myMove.equals("Rock")) {
System.out.println("Rock beats scissors, a win for me!");
myCount++;
}
else if(rps.equals('R') && myMove.equals("Paper")) {
System.out.println("Paper beats rock, a win for me!");
myCount++;
}
else if(rps.equals('S') && myMove.equals("Paper")) {
System.out.println("Scissors beats paper, a win for you!");
userCount++;
}
else if(rps.equals('R') && myMove.equals("Scissors")) {
System.out.println("Rock beats scissors, a win for you!");
userCount++;
}
else if(rps.equals('S') && myMove.equals("Paper")) {
System.out.println("Paper beats rock, a win for you!");
userCount++;
}
gameCount++;
System.out.println("Please enter Play if you want to play the game again or anything else to Stop.");
play = scan.nextLine();
}
'''
Try this out
while (true) {
System.out.println("Insert question code:");
String question = scanner.nextLine();
if(question.equals("quit")){
break;
}
System.out.println("Insert answer code:");
String answer = scanner.nextLine();
if(answer.equals("quit")){
break;
}
}
I am a student of 2 months so bear with me here.
I am trying to show my friend a Rock, Paper, Scissors game in action. I've successfully created RockPaperScissors.exe using Launch4j.
Now when I click the game's executable file I get the console to open. But when my friend tries to do so, he gets the console with no words in it, if he tries to type it closes.
Is it possible to have an executable file force the console up? Do I need to change some part of my code in order to have that happen?
Code is below in case I need to add something to make this work.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
/***** CONSTANT SECTION *****/
public static void main(String[] args)
{
/***** DECLARATION SECTION *****/
Scanner keyboard;
Random rndGen;
char computerChoice;
int playerScore, compScore;
int winner, compInt;
String name;
String userChoice;
/***** INITIALIZATION SECTION *****/
keyboard = new Scanner(System.in);
rndGen = new Random();
computerChoice = ' ';
winner = -1;
compInt = -1;
playerScore = 0;
compScore = 0;
/***** INTRO SECTION *****/
System.out.print("What is your name? ");
name = keyboard.next();
System.out.println("\nHi " + name + ".");
System.out.println("\nLet's play Rock, Paper, Scissors!");
System.out.println("Best out of 3 wins.");
/***** INPUT SECTION *****/
while (playerScore < 2 && compScore < 2)
{
System.out.print("\nEnter your choice. Type R for rock, P for paper, or S for scissors: ");
//takes a char entry and changes it into a string, upper cases the entry, and then take the first letter of the string
userChoice = keyboard.next();
userChoice = userChoice.toUpperCase();
while (!(userChoice.equals("R") || userChoice.equals("P") || userChoice.equals("S")))
{
System.out.println("Invalid entry.");
System.out.println("");
System.out.print("Enter your choice. Type R for rock, P for paper, or S for scissors: ");
userChoice = keyboard.next();
userChoice = userChoice.toUpperCase();
}
/***** PROCESSING SECTION *****/
compInt = rndGen.nextInt(3);
if (compInt == 0)
{
computerChoice = 'R';
}
else if (compInt == 1)
{
computerChoice = 'P';
}
else
{
computerChoice = 'S';
}
winner = RockPaperScissors.decideWinner(userChoice,computerChoice);
/***** OUTPUT SECTION *****/
System.out.printf(name + " chose %s%nComputer chose %c%n",userChoice,computerChoice);
switch(winner)
{
case 0: System.out.println("It's a tie!");
break;
case 1: System.out.println(name + " wins!");
playerScore = playerScore + 1;
break;
case 2: System.out.println("Computer won!");
compScore = compScore + 1;
break;
default: System.out.println("Invalid choice. Try again");
break;
}
System.out.println(name + ": " + playerScore + ", Computer: " + compScore);
}
if (playerScore > compScore)
{
System.out.println("\n" + name + " is the winner!!!");
}
else
{
System.out.println("\nSorry, the computer wins this time.");
}
keyboard.close();
System.out.println("Thanks for playing!");
}
/***** STATIC METHODS *****/
//Given two characters (R, P or S) determines //winner user rock paper scissors rules. Error check
//done in main
public static int decideWinner(String p1,char p2)
{
String combo;
combo = String.format("%s%c",p1,p2);
if ((combo.equals("RS")) || (combo.equals("PR")) || (combo.equals("SP")))
{
return 1;
}
else if ((combo.equals("RP")) || (combo.equals("PS")) || (combo.equals("SR")))
{
return 2;
}
else if ((combo.equals("PP")) || (combo.equals("SS")) || (combo.equals("RR")))
{
return 0;
}
else
{
return -1;
}
}
}
I'm attempting to create a game of "Rock Paper Scissors Lizard Spock", and want the user to be able to put in either the integers assigned to the variables (Rock=0, Paper=1, Scissors=2, Lizard=3 and Spock=4) and also be able to enter the words "Rock", "Paper", "Scissors", "Lizard" or "Spock". Could you help me include a part of the code where I can assign the string inputs to integers. I also do not want to change the main framework of the code. I also know that the website says not to paste the entire file, but I cannot think of another way to show my problem. Please note that I have been using a website called SoloLearn. Any help would be greatly appreciated.
import java.util.Scanner;
public class RockPaperScissorsLizardSpock {
final static int ROCK = 0;
final static int PAPER = 1;
final static int SCISSORS = 2;
final static int LIZARD = 3;
final static int SPOCK = 4;
public static void main(String[] args) {
double r = Math.random();
int computerChoice = (int)(3.0 * r);
Scanner input = new Scanner(System.in);
System.out.print("Enter 0 for Rock, 1 for Paper, 2 for Scissors, 3 for Lizard, 4 for Spock: ");
int playerChoice = input.nextInt();
System.out.println(computerChoice);
int playerChoice = 0;
switch (playerChoice) {
case "Rock":
playerChoice = 0;
break;
case "Paper":
playerChoice = 1;
break;
case "Scissors":
playerChoice = 2;
case "Lizard":
playerChoice = 3;
case "Spock":
playerChoice = 4;
if (computerChoice == playerChoice) {
System.out.println("Tie");
}
else if (computerChoice == ROCK && playerChoice == SCISSORS) {
System.out.println("I chose Rock,You chose Scissors, Rock crushes Scissors, You lose.");
}
else if (computerChoice == SCISSORS && playerChoice == PAPER) {
System.out.println("I chose Scissors, You chose Paper, Scissors cut Paper, You lose.");
}
else if (computerChoice == PAPER && playerChoice == ROCK) {
System.out.println("I chose Paper,You chose Rock, Paper covers Rock, You lose.");
}
else if (computerChoice == LIZARD && playerChoice == PAPER) {
System.out.println("I chose Lizard, You chose Paper, Lizard eats Paper, You lose.");
}
else if (computerChoice == SPOCK && playerChoice == SCISSORS) {
System.out.println("I chose Spock, You chose Scissors, Spock smashes Scissors, You lose.");
}
else if (computerChoice == ROCK && playerChoice == LIZARD) {
System.out.println("I chose Rock, You chose Lizard, Rock crushes Lizard, You lose.");
}
else if (computerChoice == SCISSORS && playerChoice == LIZARD) {
System.out.println("I chose Scissors, You chose Lizard, Scissors decapitates Lizard, You lose.");
}
else if (computerChoice == SPOCK && playerChoice == PAPER) {
System.out.println("I chose Spock, You chose Paper, Paper disproves Spock, You lose.");
}
else if (computerChoice == SPOCK && playerChoice == ROCK) {
System.out.println("I chose Spock, You chose Rock, Spock vaporizes Rock, You lose.");
}
else if (computerChoice == SCISSORS && playerChoice == ROCK) {
System.out.println("I chose Scissors, You chose Rock, Rock crushes Scissors, You win.");
}
else if (computerChoice == PAPER && playerChoice == SCISSORS) {
System.out.println("I chose Paper, You chose Scissors, Scissors cut Paper, You win.");
}
else if (computerChoice == ROCK && playerChoice == PAPER) {
System.out.println("I chose Rock, You chose Paper, Paper covers Rock,You win.");
}
else if (computerChoice == PAPER && playerChoice == LIZARD) {
System.out.println("I chose Paper, You chose Lizard, Lizard eats Paper, You win.");
}
else if (computerChoice == SCISSORS && playerChoice == SPOCK) {
System.out.println("I chose Scissors, You chose Spock, Spock smashes Scissors, You win.");
}
else if (computerChoice == LIZARD && playerChoice == ROCK) {
System.out.println("I chose Lizard, You chose Rock, Rock crushes Lizard, You win.");
}
else if (computerChoice == LIZARD && playerChoice == SCISSORS) {
System.out.println("I chose Lizard, You chose Scissors, Scissors decapitates Lizard, win.");
}
else if (computerChoice == PAPER && playerChoice == SPOCK) {
System.out.println("I chose Paper, You chose Spock, Paper disproves Spock, You win.");
}
else if (computerChoice == ROCK && playerChoice == SPOCK) {
System.out.println("I chose Rock, You chose Spock, Spock vaporizes Rock, You win.");
}else{
System.out.println("Error");
}
}
}
}
If you want that your user can input 2 Values for 1 condition you can convert the value from playerChoice to String for a temp String and then make a switch case for it like the following:
String tempString = Integer.toString(playerChoice);
switch (tempString) {
case "0":
case "Rock":
playerChoice = 0;
break;
case "1":
case "Paper":
playerChoice = 1;
break;
case "2":
case "Scissors":
playerChoice = 2;
break;
case "3":
case "Lizard":
playerChoice = 3;
break;
case "4":
case "Spock":
playerChoice = 4;
break;
}
You could put your allowed inputs in a map, key being the text and value being the associated number:
private static final Map<String, Integer> ALLOWED_INPUTS = Collections.unmodifiableMap(Map.of(
"ROCK", 0,
"PAPER", 1,
"SCISSORS", 2,
"LIZARD", 3,
"SPOCK", 4
));
Then, in your main function, check if the map contains a key that corresponds to the user input, if so get the corresponding value. If not, check if the user entered a number. Keep looping while the resulting number either way isn't in the map's values.
Scanner in = new Scanner(System.in);
int playerChoice = -1;
String input;
while(!ALLOWED_INPUTS.containsValue(playerChoice)) {
input = in.nextLine();
if (ALLOWED_INPUTS.containsKey(input))
playerChoice = ALLOWED_INPUTS.get(input);
else {
try {
playerChoice = Integer.parseInt(input);
} catch(NumberFormatException e) {}
}
}
System.out.println("You choosed choice number " + playerChoice);
Assuming : Either Words or Integers are entered as inputs.
Steps for this solution:
Always Entering String Input: String choice = input.next();
Checking if choice contains only digits, if yes,convert this to Integer else don't do anything.
if entered input is words, it will go to switch first,then set playerChoice and run properly.
if entered input is digit, it will assign converted integer to playerChoice first, then it will go to switch but as no default exists, it will run properly.
String choice = input.next();
if (choice.matches("\\d+"))
playerChoice = Integer.parseInt(choice);
switch (choice.toUpperCase()) {
case "ROCK":
playerChoice = 0;
break;
case "PAPER":
playerChoice = 1;
break;
case "SCISSORS":
playerChoice = 2;
break;
case "LIZARD":
playerChoice = 3;
break;
case "SPOCK":
playerChoice = 4;
break;
}
I am doing a project to make a user login, then ask the user to select which game to play, then write the code for the game. I have done everything apart from being able to choose to between the 2 games. Any tips on how to do this would greatly help!
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.io.InputStreamReader;
public class SkillsDemo31 {
private static boolean again = true;
private static int action;
public static void main(String[] args) throws IOException {
//***************************
//Login
//***************************
class User {
User (String username, String password)
{
this.username = username;
this.password = password;
}
String GetUsername() {return username;}
String GetPassword() {return password;}
private String username;
private String password;
}
String greeting = "Hello";
String username;
String password;
// Used to hold the instance of a user who successfully logged in
User loggedInUser = null;
// Create an empty list to hold users
List<User> listOfUsers = new ArrayList<>();
// Add 3 users to the list
listOfUsers.add(new User("Gerry","spintown"));
listOfUsers.add(new User("Evelyn","poker"));
listOfUsers.add(new User("Joan","bonus"));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("*** Welcome to the program ***\n");
System.out.println(greeting);
System.out.println("Please type your username :");
username = br.readLine();
System.out.println("Please type your password :");
password = br.readLine();
for (User user : listOfUsers)
{
if (user.GetUsername().equals(username))
{
if (user.GetPassword().equals(password))
{
loggedInUser = user;
// when a user is found, "break" stops iterating through the list
break;
}
}
}
// if loggedInUser was changed from null, it was successful
if (loggedInUser != null)
{
System.out.println("User successfully logged in: "+loggedInUser.GetUsername());
}
else
{
System.out.println("Invalid username/password combination");
}
//**********************************
//Choice of Games
//**********************************
again = true;
action = 0;
while (again)
{
System.out.println("Please type 1 for Rock, Paper, Scissors or 2 for Play pick up sticks:");
action = Integer.parseInt(br.readLine());
if (action == 1)
{
System.out.println("\nYou have chosen to play Rock, Paper, Scissors");
}
else if (action == 2)
{
System.out.println("\nYou have chosen to Play pick up sticks");
again = false;
}
//******************************
//Rock,Paper,Scissors
//********************************
Random rnd = new Random();
int input;
int score = 0;
int B = 1;
System.out.println("Pick 1,2, or 3 for:");
System.out.println("Rock (1), Paper(2), or Scissors (3)");
while (B != 0) {
// 1 = rock
// 2 = paper
// 3 = scissors
// N= Integer.parseInt(br.readLine())
int Rock = 1, Paper = 2, Scissor = 3;
input = Integer.parseInt(br.readLine());
int randomNumber = rnd.nextInt(3 - 1 + 1) + 1;
if (randomNumber == Rock) {
if (input == Rock) {
System.out.println("Rock Vs. Rock: Tie");
} else if (input == Paper) {
System.out.println("Paper Vs. Rock: You Win!");
System.out.println("Congratulations!");
score++;
} else if (input == Scissor) {
System.out.println("Scissors Vs. Rock: You Lose");
}
} else if (randomNumber == Paper) {
if (input == Rock) {
System.out.println("Rock Vs. Paper: You Loose");
} else if (input == Paper) {
System.out.println("Paper Vs. Paper: Tie");
} else if (input == Scissor) {
System.out.println("Scissors Vs. Paper: You Win");
System.out.println("Congratulations!");
score++;
}
} else if (randomNumber == Scissor) {
if (input == Rock) {
System.out.println("Rock Vs. Scissors: You Win");
System.out.println("Congratulations!");
score++;
} else if (input == Paper) {
System.out.println("Paper Vs. Scissors: You Loose");
} else if (input == Scissor) {
System.out.println("Scissors Vs. Scissors: Tie");
}
}
int Y=5, N=10;
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press(5) For Yes/(10) For No");
input = Integer.parseInt(br.readLine());
if(input==Y){
B=1;
System.out.println("Rock, Paper,Scissors");
}
else if(input==N)
{System.exit(0);
System.out.println("Have A Good Day!");
}
//***********************
//Pick Up Sticks
//***********************
Scanner scanner = new Scanner(System.in);
while (true) {
int numSticks = 21;
System.out.println("Would You Like to go first? (Yes/No)");
Scanner input1 = new Scanner(System.in);
String goFirst = input1.nextLine();
Scanner take = new Scanner (System.in);
int numToTake = 0;
int score2 = 0;
while (numSticks > 0) {
if (goFirst.equals("Yes") || goFirst.equals("yes")) {
System.out.println("There are " + numSticks + " sticks ");
System.out.println("How many sticks do you want to take (1 or 2)");
numToTake = take.nextInt();
if (numToTake > 2) {
numToTake = 2;
}
else if (numToTake < 1) {
numToTake = 1;
}
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println("You lose");
System.out.println("Your score is " + score );
}
else {
if((numSticks - 2) % 3 == 0 || numSticks - 2 == 0) {
numToTake = 1;
}
else {
numToTake = 2;
}
System.out.println("Computer takes " + numToTake + " sticks " );
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println(" You win ");
score++;
System.out.println("Your score is " + score );
}
}
}
else {
if((numSticks - 2) % 3 == 0 || numSticks - 2 == 0) {
numToTake = 1;
}
else {
numToTake = 2;
}
System.out.println("Computer takes " + numToTake + " sticks " );
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println("You win");
score++;
System.out.println("Your score is " + score );
}
else {
System.out.println("There are " + numSticks + " sticks ");
System.out.println("How many sticks do you want to take (1 or 2)");
numToTake = take.nextInt();
if (numToTake > 2) {
numToTake = 2;
}
else if (numToTake < 1){
numToTake = 1;
}
numSticks = numSticks - numToTake;
if(numSticks <0){
System.out.println("You win");
score++;
}
}
}
}
System.out.println("Do you want to play again, type (5) for yes or (10) for no");
if (scanner.nextLine().equals("10")) {
break;
}
}
}
}
}
You should create for every game a class and create a start method there to start the game based on your user input for example:
System.out.println("Please type 1 for game 1 or 2 for game2:");
action = Integer.parseInt(br.readLine());
if (action == 1)
{
System.out.println("\nYou have chosen to game 1");
Game1 game1 = new Game1();
game1.start();
}
else if (action == 2)
{
System.out.println("\nYou have chosen game 2");
Game2 game2 = new Game2();
game2.start();
}
This code is based on your code.
Bob, I just check through your code.
According to what I saw, my understanding of your question is that "After user login and selected the game type, both game would run subsequently, while you only want to run the game user chose".
If that is the case, then the solution is easy:
Take the games code parts out from the
while(again){
// In this block, only keeps your user choice code.
}
block. That block would be just for getting user's choice.
After that choice block, you get your users' choice from variable "action". Now you just need to add a if block as below:
if(action == 1){
// Put your Rock,Paper,Scissors game code here, as user chose 1
//******************************
//Rock,Paper,Scissors
//********************************
...
}else if(action == 2){
// Put your Pick Up Sticks game code here, as user chose 2.
//***********************
//Pick Up Sticks
//***********************
...
}
As you only want to run one game at a time, you need a "IF" condition to tell the code which game to run.
So just "IF" is enough, but separating the "Choice" part and "Game" part, from my opinion, would make the code more simpler and easier to be understood.
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();
}
}
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.
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
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();