Hey guys having some trouble with a multi part question. I'm trying to get a game of rock paper scissors done, when i try to test the code using the playRound method I have to input my choice over and over again and then it just prints out draw, you are the winner and the computer is the winner over and over, can anyone tell me where im going wrong ?
import java.util.Scanner;
import java.util.Random;
/**
* A class that will play a game of rock paper scissors.
*
* #author (your name)
* #version (a version number or a date)
*/
public class RockPaperScissors
{
private Scanner reader;
private int yourScore;
private int computerScore;
private Random ran = new Random();
public RockPaperScissors()
{
reader = new Scanner(System.in);
yourScore = 0;
computerScore=0;
Random ran = new Random();
}
public void printPrompt()
{
System.out.println("Enter your choice, paper, rock or scissors >");
String userChoice = userChoice();
System.out.println();
System.out.println();
System.out.println("Enter your choice, paper, rock or scissors >"+ userChoice);
}
public final String userChoice()
{
String userChoice= reader.next();
return userChoice;
}
public String computerChoice()
{
String compMove = ("");
int cpuChoice = ran.nextInt(3);
switch(cpuChoice)
{
case 0:
{
compMove = ("rock");
break;
}
case 1:
{
compMove = ("paper");
break;
}
case 2:
{
compMove = ("scissors");
break;
}
}
return (compMove);
}
public String findWinner(String yourChoice, String computerChoice)
{
yourChoice = userChoice();
computerChoice = computerChoice();
String Winner= null;
if (yourChoice.equals(computerChoice))
{
Winner = ("draw");
}
if (yourChoice.equals("rock"))
{
if (computerChoice.equals("paper"))
{
computerScore++;
Winner = ("computer");
}
else if (computerChoice == "scissors")
{
yourScore++;
Winner = ("you");
}
}
if (yourChoice.equals("paper"))
{
if (computerChoice.equals("scissors"))
{
computerScore++;
Winner = ("computer");
}
else if (computerChoice.equals("rock"))
{
yourScore++;
Winner = ("you");
}
}
if (yourChoice.equals("scissors"))
{
if (computerChoice.equals("rock"))
{
computerScore ++;
Winner = ("computer");
}
else if (computerChoice.equals("paper"))
{
yourScore++;
Winner = ("you");
}
}
if (!yourChoice.equals("rock||paper||scissors"))
{
computerScore++;
Winner = ("computer");
}
return Winner;
}
public void playRound()
{
printPrompt();
String computerChoice=computerChoice();
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
String findWinner = findWinner(computerChoice,userChoice);
{
if (findWinner.equals("draw"));
System.out.println("This game is a draw");
if (findWinner.equals("you"));
System.out.println("You are the winner");
if (findWinner.equals("computer"));
System.out.println("The computer is the winner");
}
System.out.println("You have " + yourScore + "and the computer has "+ computerScore);
}
}
The semicolon at the end of your if statements means that the if statement is COMPLETE. The lines immediately following your if statements are then stand-alone, they do not "belong" to the if statements...which is why they always run.
Change:
if (findWinner.equals("draw"));
System.out.println("This game is a draw");
To:
if (findWinner.equals("draw"))
System.out.println("This game is a draw");
Or even better:
if (findWinner.equals("draw")) {
System.out.println("This game is a draw");
}
Any advice on how i can get my initial choice to be saved so I don't
have to keep typing it in ?
In findWinner(), you're calling userChoice() and computerChoirce() AGAIN. At that point, the values are already in the parameters that were passed in, so you don't need those. Comment them out or remove them:
public String findWinner(String yourChoice, String computerChoice)
{
// You don't need these two lines:
//yourChoice = userChoice();
//computerChoice = computerChoice();
// ... other existing code ...
}
Then, in playRound(), you are calling both printPrompt() and userChoice(), which each have their own input mechanism:
printPrompt();
String computerChoice=computerChoice();
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
I'd get rid of printPrompt() and just do:
// printPrompt();
String computerChoice=computerChoice();
System.out.print("Enter your choice, paper, rock or scissors >");
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
You have some broken logic in findWinner(). This does not do what you think it does:
if (!yourChoice.equals("rock||paper||scissors"))
{
computerScore++;
Winner = ("computer");
}
I think what you were trying to do is make the computer win if the user did not type in "rock", "paper", or "scissors"? If so, change your if statements to else if statements and add a final else block:
public String findWinner(String yourChoice, String computerChoice)
{
String Winner = "";
if (yourChoice.equals(computerChoice))
{
Winner = "draw";
}
else if (yourChoice.equals("rock"))
{
if (computerChoice.equals("paper"))
{
computerScore++;
Winner = "computer";
}
else if (computerChoice.equals("scissors"))
{
yourScore++;
Winner = "you";
}
}
else if (yourChoice.equals("paper"))
{
if (computerChoice.equals("scissors"))
{
computerScore++;
Winner = "computer";
}
else if (computerChoice.equals("rock"))
{
yourScore++;
Winner = "you";
}
}
else if (yourChoice.equals("scissors"))
{
if (computerChoice.equals("rock"))
{
computerScore ++;
Winner = "computer";
}
else if (computerChoice.equals("paper"))
{
yourScore++;
Winner = "you";
}
}
else // user did not type "rock", "paper", or "scissors"!
{
computerScore++;
Winner = ("computer");
}
return Winner;
}
Lastly, MAJOR bug, you SWAPPED the order of your parameters when you called findWinner().
Change:
String findWinner = findWinner(computerChoice, userChoice);
To:
String findWinner = findWinner(userChoice, computerChoice);
Hope that helps!
Related
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;
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have been frustrated with this code. The goal is to create a rock paper scissors game, best of 3. I have tried to make a "while" loop but I've got it all wrong and ended up scrapping it back to what I started with, a non-looping code.
If anyone can enlighten me how to make it loop until the computer or player gets a score of 3 wins, I would be so grateful!! Thank you so much
Sorry I should clarify, it needs to loop until the user or computer has 3 wins, so they rebattle until the user or computer reaches 3 wins
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main(String[] args)
{
Scanner key;
Random randGen;
char userChoice, computerChoice;
int winner, compInt;
int computerScore;
int userScore;
int scoreCounter;
/***** INITIALIZATION SECTION *****/
key = new Scanner(System.in);
randGen = new Random();
userChoice = ' ';
computerChoice = ' ';
//winner = -1;
compInt = -1;
computerScore = 0;
userScore = 0;
scoreCounter = 0;
System.out.println("What is your name?");
String name = key.nextLine();
System.out.println(name + " play rock, paper, or scissors with me!!");
/***** INPUT SECTION *****/
System.out.println("Please enter R for rock, P for paper, or S for scissors:");
userChoice = key.next().toUpperCase().charAt(0);
//key.close();
/***** PROCESSING SECTION *****/
compInt=randGen.nextInt(3);
if (compInt == 0)
{
computerChoice = 'R';
}
else if (compInt == 1)
{
computerChoice = 'P';
}
else if (compInt == 2)
{
computerChoice = 'S';
}
winner = RockPaperScissors.decideWinner(userChoice,computerChoice);
/***** OUTPUT SECTION *****/
System.out.printf("Player: %c%nComputer: %c%n", userChoice, computerChoice);
switch (winner)
{
case 0:
System.out.println("It's a tie!");
System.out.println(name + ": " + userScore + ", Computer:" + computerScore );
break;
case 1:
System.out.println("You won!");
userScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore );
break;
case 2:
System.out.println("Computer won!");
computerScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore );
break;
default:
System.out.println("Invalid choice, try again.");
break;
}
//System.out.println("Thanks for playing!);
}
/***** STATIC METHODS *****/
/**Description: given two characters (R,P, or S) determines winner using rock
* paper rules. Assume input is valid and error checking is done in main
* programme. **/
public static int decideWinner(char p1,char p2)
{
String combo;
combo = String.format("%c%c", p1, p2);
switch(combo)
{
case "RS":
case "PR":
case "SP":
return 1;
case "RP":
case "PS":
case "SR":
return 2;
case "RR":
case "PP":
case "SS":
return 0;
}
return -1;
}
}
/***************************************************
while(userScore == 3)
{
System.out.println("You won the game" +name+ "! Congratulations");
scoreCounter++;
}
while(computerScore == 3)
{
System.out.println("Sorry " +name+ ", Computer won...");
scoreCounter++;
}
**************************************************/
Try splitting your code in methods that each have their own task, that way u can more easily lay out and control the behaviour of your program. E.g. in the case of user input, you can recursively call the method in case of invalid input.
For the while loop, I simply added a counter that increases after every game, until 3.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
private static int totalGames = 0;
public static void main(String[] args)
{
Scanner key;
Random randGen;
char userChoice, computerChoice;
int winner;
int computerScore;
int userScore;
/***** INITIALIZATION SECTION *****/
key = new Scanner(System.in);
randGen = new Random();
computerChoice = ' ';
//winner = -1;
computerScore = 0;
userScore = 0;
System.out.println("What is your name?");
String name = key.nextLine();
System.out.println(name + " play rock, paper, or scissors with me!!");
while(totalGames < 3) {
userChoice = getUserChoice(key, false);
/* PROCESSING SECTION */
computerChoice = getComputerChoice(computerChoice, randGen.nextInt(3));
winner = RockPaperScissors.decideWinner(userChoice, computerChoice);
totalGames++;
/* OUTPUT SECTION */
System.out.printf("Player: %c%nComputer: %c%n", userChoice, computerChoice);
switch (winner) {
case 0:
System.out.println("It's a tie!");
System.out.println(name + ": " + userScore + ", Computer:" + computerScore);
break;
case 1:
System.out.println("You won!");
userScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore);
break;
case 2:
System.out.println("Computer won!");
computerScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore);
break;
default:
System.out.println("Invalid choice, try again.");
break;
}
}
//System.out.println("Thanks for playing!);
}
private static char getComputerChoice(char computerChoice, int compInt) {
if (compInt == 0)
{
computerChoice = 'R';
}
else if (compInt == 1)
{
computerChoice = 'P';
}
else if (compInt == 2)
{
computerChoice = 'S';
}
return computerChoice;
}
private static char getUserChoice(Scanner key, boolean retry) {
char userChoice;
/* INPUT SECTION */
if(retry)
System.out.println("You entered an invalid input, please try again...");
System.out.println("Please enter R for rock, P for paper, or S for scissors:");
try {
userChoice = key.next().toUpperCase().charAt(0);
if(userChoice != 'R' && userChoice != 'P' && userChoice != 'S')
return getUserChoice(key, true);
} catch (Exception e){
return getUserChoice(key, true);
}
return userChoice;
}
/***** STATIC METHODS *****/
/**Description: given two characters (R,P, or S) determines winner using rock
* paper rules. Assume input is valid and error checking is done in main
* programme. **/
public static int decideWinner(char p1,char p2)
{
String combo;
combo = String.format("%c%c", p1, p2);
switch(combo)
{
case "RS":
case "PR":
case "SP":
return 1;
case "RP":
case "PS":
case "SR":
return 2;
case "RR":
case "PP":
case "SS":
return 0;
}
return -1;
}
}
/***************************************************
while(userScore == 3)
{
System.out.println("You won the game" +name+ "! Congratulations");
scoreCounter++;
}
while(computerScore == 3)
{
System.out.println("Sorry " +name+ ", Computer won...");
scoreCounter++;
}
**************************************************/
I am trying to figure out where to put the loop that when the user enters any value other than "rock", "paper" or "scissors" the program stays in the loop and displays "Invalid entry" while requesting the user to enter again.
Any help is much appreciated.
As it stands now, the program will display "Invalid entry" but then continues without asking the user to try again.
import java.util.Scanner; // Import the Scanner class
import java.util.Random; // Import the random class for game
/**
*/
public class Challenge17
{
// Method to determine the random choice of computer
public static String getComputerChoice(Random random)
{
int number;
number = random.nextInt(3) + 1;
String computerChoice;
switch (number)
{
case 1:
computerChoice = "rock";
break;
case 2:
computerChoice = "paper";
break;
case 3:
computerChoice = "scissors";
break;
default:
computerChoice = "";
}
return computerChoice;
}
// Method to display the menu for choices
public static void displayChoice( )
{
System.out.println("Game Options\n----------\n"
+ "1: rock\n2: paper\n3: scissors");
}
// Method to request and hold user choice for game
public static String getUserInput(Scanner keyboard)
{
String userInput;
System.out.println("Enter your choice: ");
userInput = keyboard.nextLine();
return userInput;
}
// Method to determine winner
public static String determineWinner(String computerChoice, String userInput)
{
String winner = "Tie Game!"; // Default display Tie game
String message = ""; // To determine the message for winner
String displayMessage; // To display the message for winner
// Custom messages below
String rockMessage = "Rock smashes scissors";
String scissorsMessage = "Scissors cuts paper";
String paperMessage = "Paper wraps rock";
boolean loop = false;
if(computerChoice.equals("rock") && userInput.equalsIgnoreCase("scissors"))
{
winner = " Computer wins!";
message = rockMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("rock") && computerChoice.equals("scissors"))
{
winner = "You win!";
message = rockMessage;
loop = true;
}
if(computerChoice.equals("scissors") && userInput.equalsIgnoreCase("paper"))
{
winner = " Computer wins!";
message = scissorsMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("scissors") && computerChoice.equals("paper"))
{
winner = "You win!";
message = scissorsMessage;
loop = true;
}
if(computerChoice.equals("paper") && userInput.equalsIgnoreCase("rock"))
{
winner = " Computer wins!";
message = paperMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("rock") && computerChoice.equals("scissors"))
{
winner = "You win!";
message = paperMessage;
loop = true;
}
else
{
System.out.println("Invalid entry.");
loop = false;
}
displayMessage = winner + " " + message;
return displayMessage;
}
// Main method to initiate and execute game
public static void main(String[] args)
{
Random random = new Random(); // To call the random class
Scanner keyboard = new Scanner(System.in); // To call the scanner class
String computerChoice; // Hold computer input
String userInput; // Hold user input
String input; // Hold input for repeat
char repeat; // Character for repeat
do
{
displayChoice(); // Call method to display the choices
computerChoice = getComputerChoice(random); // Hold the PC random choice
userInput = getUserInput(keyboard); // To get the user input
System.out.println("You chose: " + userInput + " computer chose: \n"
+ computerChoice);
System.out.println(determineWinner(computerChoice, userInput));
// Does the user want to play again
System.out.println("Would you like to play again?");
System.out.print("Enter Y for yes, or N for no: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
while (repeat == 'Y' || repeat == 'y');
}
}
From my understanding i'm pretty sure you want this kind of a loop
public static String getUserInput(Scanner keyboard)
{
String userInput;
System.out.println("Enter your choice: ");
userInput = keyboard.nextLine();
while(!userInput.equals("rock")&&!userInput.equals("paper")&&!userInput.equals("scissors"))
{
System.out.println("Invalid Entry, Please re-enter your choice:");
userInput = keyboard.nextLine();
} //It wont go out of the loop unless it's one of the 3 choices
return userInput;
}
You could create a Boolean method.
private Boolean checkUserInput(String input) {
if(!input.equalsIgnoreCase("rock") && !input.equalsIgnoreCase("paper") && !input.equalsIgnoreCase("scissors")) return false;
return true;
Then you do the check before you determine the winner like if true then run the determineWinner(computerChoice, userInput) code else it doesn't.
That way, you can edit the code and add functionalities in the future if need be.
So my task today is to make a rock paper scissors game using methods. My first problem with my code is that I need it to ask the user if they want to play again or not. (y or n) Also, I need to implement scoring, 1 point if user wins, -1 if they lose, and for each time they play again add that score to total score. Any ideas on how to implement this? or what I need to change to my code. Also I am a rookie so sorry for the ugly formatting and feel free to critic every little detail, ill soak up all the information I can.
public static void main(String[] args){
boolean tie = true;
do{
String computer = computerChoice();
String user = userChoice();
tie = (computer.compareTo(user) == 0);
determineWinner(computer, user);
}while(tie);
}
public static String computerChoice( ){
Random rand = new Random();
int cinput = rand.nextInt(3)+ 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static String userChoice(){
Scanner sc = new Scanner (System.in);
String user = "default";
do{
System.out.println("choose your weapon(Paper,Scissors or Rock)");
user = sc.nextLine();
}
while (isValidChoice (user) == false);
return user;
}
public static boolean isValidChoice(String choice){
boolean status;
if (choice.compareTo("Rock")== 0)
status = true;
else if (choice.compareTo("Paper")== 0)
status = true;
else if (choice.compareTo("Scissors")== 0)
status = true;
else{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static boolean determineWinner(String computer, String user){
System.out.println (" Computer Choice: " + computer);
System.out.println ("Your Choice : " + user);
if (computer.compareTo( "Rock" ) == 0 && user.compareTo ("Scissors") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Scissors")== 0 && user.compareTo("Paper") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Rock") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Rock") == 0 && user.compareTo("Paper") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Scissors") == 0 && user.compareTo("Rock") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Scissors") == 0)
System.out.println (" You win!!");
else if (computer.compareTo(user) == 0 ){
System.out.println(" Tie! the game must be played again.");
return false;
}
return true;
}
}
a output that my professor gave us as an example is:
Choose your weapon!
1. Paper
2. Scissors
3. Rock
5
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose rock!
I have been vanquished!
We have matched wits 1 times, and your score is 1
Do you want to play again (y or n)? y
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose paper!
We are equally matched. You are a worthy adversary.
We have matched wits 2 times, and your score is 1
Do you want to play again (y or n)? n
Here is the finished code. I added two functions, one to call the actual game and one to check if the player wanted to play again. Also, there is the concluding sentence in the end
import java.util.Random;
import java.util.Scanner;
public class RPC
{
public static Scanner sc = new Scanner(System.in);
public static int score = 0;
public static int gameCount = 0;
public static void main(String[] args)
{
play();
while (playAgain())
{
play();
}
}
public static void play()
{
String computer = computerChoice();
String user = userChoice();
determineWinner(computer, user);
}
public static String computerChoice()
{
Random rand = new Random();
int cinput = rand.nextInt(3) + 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static boolean playAgain()
{
System.out.println("Play again?(y/n)");
String input = sc.nextLine();
if (input.toLowerCase().equals("y"))
{
return true;
} else if (input.toLowerCase().equals("n"))
{
return false;
} else
{
System.out.println("Invalid Input");
return playAgain();
}
}
public static String userChoice()
{
String user = "default";
do
{
System.out.println("choose your weapon(Paper,Scissors or Rock)");
user = sc.nextLine();
} while (!isValidChoice(user));
return user;
}
public static boolean isValidChoice(String choice)
{
boolean status;
if (choice.equals("Rock"))
status = true;
else if (choice.equals("Paper"))
status = true;
else if (choice.equals("Scissors"))
status = true;
else
{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static void determineWinner(String computer, String user)
{
gameCount++;
System.out.println(" Computer Choice: " + computer);
System.out.println("Your Choice : " + user);
if (computer.equals("Rock") && user.equals("Scissors"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Scissors") && user.equals("Paper"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Paper") && user.equals("Rock"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Rock") && user.equals("Paper"))
{
score++;
System.out.println(" You win!!");
}
if (computer.equals("Scissors") && user.equals("Rock"))
{
score++;
System.out.println(" You win!!");
}
if (computer.equals("Paper") && user.equals("Scissors"))
{
score++;
System.out.println(" You win!!");
} else if (computer.equals(user))
{
System.out.println(" Tie! the game must be played again.");
}
System.out.println("We have matched wits" + gameCount + "times, and your score is" + score);
return;
}
}
Hi I am making a simple rock, paper, scissors game and was having some trouble getting my compare method to get executed. The game prompts the user for input, and then using the computersTurn method to allow the computer to randomly select rock paper or scissors. When I try and pass both these values into my compare method, it doesn't seem to work. Any suggestions would be awesome!
import java.util.Scanner;
public class sillyGame {
public static void compare (String choice1, String choice2)
{
if (choice1.equals(choice2))
{
System.out.println("The result is a tie!");
}
if (choice1.contains("rock"))
{
if (choice2.contains("scissors"))
{
System.out.println("rock wins");
}
if (choice2.contains("paper"))
{
System.out.println("paper wins");
}
}
if (choice1.contains("scissors"))
{
if (choice2.contains("rock"))
{
System.out.println("rock wins");
}
if (choice2.contains("paper"))
{
System.out.println("scissors wins");
}
}
if (choice1.contains("paper"))
{
if (choice2.contains("rock"))
{
System.out.println("paper wins");
}
if (choice2.contains("scissors"))
{
System.out.println("scissors wins");
}
}
}
public static String computersTurn(String compFinalChoice, double randomNum){
randomNum = Math.random();
if (randomNum < 0.34)
{
compFinalChoice = "rock";
}
else if(randomNum <= 0.67)
{
compFinalChoice = "paper";
}
else
{
compFinalChoice = "scissors";
}
System.out.println("The computer chooses " + compFinalChoice);
return compFinalChoice;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Do you choose rock, paper or scissors?");
String userChoice = scan.nextLine();
String computerDec = " ";
double rand = 0.0;
computersTurn(computerDec, rand);
compare(userChoice, computerDec);
}
Your computersTurn method doesn't need any parameters. You're just passing it " " and 0.0.
Try changing it to this method:
public static String computersTurn() {
// declare them here
double randomNum = Math.random();
String compFinalChoice = "";
if (randomNum < 0.34) {
compFinalChoice = "rock";
}
else if(randomNum <= 0.67) {
compFinalChoice = "paper";
}
else {
compFinalChoice = "scissors";
}
System.out.println("The computer chooses " + compFinalChoice);
return compFinalChoice;
}
And then in your main method, make sure when you call the computersTurn() method, you assign it to a String. Calling it does nothing for you; you need to keep the return value:
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Do you choose rock, paper or scissors?");
String userChoice = scan.nextLine();
String computerDec = computersTurn(); // assign it here
compare(userChoice, computerDec);
}
You cannot update a String (or a double) from a caller so I think you should re-factor computersTurn like so
public static String computersTurn() {
String choice = "scissors";
double randomNum = Math.random();
if (randomNum < 0.34) {
choice = "rock";
} else if (randomNum <= 0.67) {
choice = "paper";
}
System.out.println("The computer chooses "
+ choice);
return choice;
}
Then you can do something like this in main
String computerDec = computersTurn();
or
String userChoice = scan.nextLine();
compare(userChoice, computersTurn());