So here i am trying to create a program that takes an input as an int and then plays a game of Rock paper scissors. It seems to want to reprint statements that it shouldn't be and is skipping printing statements as well. I would love some assistance if possible. I have tried setting up print statements everywhere but it has just been more confusing.
import java.util.Scanner;
public class RPSS{
//Main method
public static void main(String[ ] argc)
{
System.out.println("Lets play rock paper scissors");
Scanner tnt = new Scanner(System.in);
String computerHand; // string variable for computer choice
String userHand; // string variable for user choice
//
String answer = "";
while (!a
nswer.equals("No") && (!answer.equals("no"))){
userHand = userHand();
computerHand = computerHand();
System.out.println("The User picks " + userHand + " " );
System.out.print("The Computer picks " + computerHand );
String winner = getWinner(computerHand, userHand);
System.out.println(winner);
System.out.println("play again?");
answer = tnt.next();
}
//Condition for the do-while loop
}
public static String userHand(){ //method for users choice in the game
//prints message to user giving them choices
System.out.println(" ");
System.out.println("1. Rock ");
System.out.println("2. Paper ");
System.out.println("3. Scissors ");
int userChoice; // user choice variable in this method
Scanner tnt = new Scanner(System.in); // creates instance of scanner class
userChoice = tnt.nextInt(); //reads user input
return getChoice(userChoice); //returns user choice to userChoice
}
public static String computerHand() //method for computer generated choice
{
int computernum = 1 + (int)(Math.random() * (( 2) +1));
return getChoice(computernum);
}
public static String getChoice(int num) //method recieving both computer hand and user hand
{
// if statements to place the correct choice
String choice = "";
if (num == 1){
choice = "Rock";
}
else if(num == 2){
choice = "Paper";
}
else if(num == 3){
choice = "Scissors";
}
return choice;
}
// Method determing the winner
public static String getWinner(String computerChoice, String userChoice)
{
computerChoice = computerHand(); //places computerChoice variable in computerhand
userChoice = userHand(); //does same for user choice
String winner="";
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println("The computer wins");
return winner;
}
else if (userChoice.equals("Paper") && computerChoice.equals("Scissors")){
System.out.println(" The computer wins");
return winner;
}
else if (userChoice.equals("Scissors") && computerChoice.equals("Rock")){
System.out.println(" The computer wins ");
return winner;
}
else if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println(" The computer wins ");
return winner;
}
else if(userChoice.equals(computerChoice))
{
System.out.println(" There is no winner");
return " ";
}
else{
return winner;
}
}
}
The first problem is that userhand() and computerHand() are being called twice per "round", once at the beginning of the while loop inside the main method and once at the beginning of the getWinner() method. Elimination of the calls at the beginning of the getWinner() method should solve the repeats.
The 2nd Problem is that instead of modifying the value of winner inside the getWinner() method before returning it, you are you are simply outputting the message via println(). an example of fixing this would be converting this:
if (userChoice.equals("Rock") && computerChoice.equals("Paper"){
System.out.println("The computer wins");
return winner;
}
to this:
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
winner = "The computer wins";
return winner;
}
another minor issue is the fact that
userChoice.equals("Rock") && computerChoice.equals("Paper")
is checked twice, id just remove the entire if else block based around the
2nd check of it
Lastly i would treat the final else clause as the player wins one and set winner to something like " The player wins "
Related
Create a program named rockPaperScissors.java
The program should validate user input.
Game should ask the user to play again and continue if yes and stop if no.
Once the user stops playing, program should print the total number of wins for the computer and
for the user.
I am trying to learn programming from a book, so I am not good at this. I need to return the values of Cwin and Uwin to the main method, but I know how to return one value to it. I also have a problem with looping the question. I cannot use arrays and could only use the basic while loops (without the (true) and break).
import java.util.*;
public class rockPaperScissors
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Play again? Type yes or no.");
String YoN= input.next();
if (YoN.equalsIgnoreCase("yes"))
{
game();
}
else
{
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
}
}
public static void game()
{
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
Scanner console = new Scanner(System.in);
Random r = new Random();
int choice = console.nextInt();
int Uwin = 0;//user win count
int Cwin = 0;//computer win count
int result = -1;
if (choice > 1 || choice < 3)
{
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
int comp = r.nextInt(3) + 1;
if (comp == 1)
{
System.out.println("Computer chose rock.");
}
if (comp == 2)
{
System.out.println("Computer chose paper.");
}
if (comp == 3)
{
System.out.println("Computer chose scissors.");
}
if (choice == 1 && result == 2)
{
Cwin++;
}
if (choice == 2 && result == 3)
{
Cwin++;
}
if (choice == 3 && result == 1)
{
Cwin++;
}
if (choice == 2 && result == 1)
{
Uwin++;
}
if (choice == 3 && result == 2)
{
Uwin++;
}
if (choice == 1 && result == 3)
{
Uwin++;
}
}
}
If you want to return multiple values from a method you may use an array that stores the values in its elements. Check here.
However for this program there is no need for returning 2 values(and you also said "I cannot use arrays"). Instead you can have 2 global variables that record the number of times the player wins and the number of times the computer wins respectively. Lets call them playerWinCount and computerWinCount.
Now that we got that down, lets look at how we allow the user to replay the game. You say that can use only "basic while loops". Fine. What we do is we declare a variable choice that holds the user's entry when prompted to replay. We initialise choice to true and then keep asking the user if he'd like to play again until he decides not to.
String choice = "yes" ;
while(choice.equalsIgnoreCase("yes"))
{
playGame() ;
System.out.print("Play again(Yes/No)? ") ;
choice = scanner.next() ;
}
The playGame() method has the code to play the game.
The way we validate the user's entry is by using a length check. If the entry is out of range(i.e. from 1 to 3 inclusive) he'll be prompted to enter again.
boolean valid = false ;
while(valid == false) // loop will run until a valid number is entered
{
System.out.print("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors: ") ;
playerPick = scanner.nextInt() ;
// validation of the user's entry
if(playerPick < 1 || playerPick > 3)
System.out.println("Invalid entry! Try again.") ;
else
valid = true ;
}
Having acquired a valid user input, the next thing we do is get a random number as the computer's pick(you've done that). Then we check who won the game and increment the number of times the winner has won. We can do this using a number of if statements like this:
// first we check if the computer and player did not pick the same thing
if(playerPick != computerPick)
{
if(playerPick == 1 && computerPick == 3) // check if the player picked rock(1) and the computer picked scissors(3)
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else if(playerPick == 3 && computerPick == 2) // check if the player picked scissors(3) and the computer picked paper(2)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else if(playerPick == 2 && computerPick == 1) // check if the player picked paper(2) and the computer picked rock(1)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else // otherwise, the computer has won this round
{
computerWinCount++ ;
System.out.println("Computer won!") ;
}
}
else
{
System.out.println("It's a tie!");
}
Or we can just combine the 3 conditions of winning with the OR operator(||) and use just 2 if statements:
if(playerPick != computerPick)
{
if((playerPick == 1 && computerPick == 3) || (playerPick == 3 && computerPick == 2) || (playerPick == 2 && computerPick == 1))
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else
{
computerWinCount++ ;
System.out.println("Computer won!");
}
}
else
{
System.out.println("It's a tie!");
}
And that's about it.
Here's the entire code:
import java.util.* ;
public class RockPaperScissors
{
static Scanner scanner = new Scanner(System.in) ;
static int playerWinCount, computerWinCount ;
public static void main(String[] args)
{
playerWinCount = 0 ;
computerWinCount = 0 ;
String choice = "yes" ;
while(choice.equalsIgnoreCase("yes"))
{
playGame() ;
System.out.print("Play again(Yes/No)? ") ;
choice = scanner.next() ;
}
System.out.println("\nNumber of times you won: " + playerWinCount) ;
System.out.println("Number of times computer won: " + computerWinCount) ;
System.out.println("Goodbye!") ;
}
public static void playGame()
{
System.out.println("") ;
Random random = new Random() ;
int playerPick = -1 ;
int computerPick = -1 ;
boolean valid = false ;
while(valid == false) // loop will run until a valid number is entered
{
System.out.print("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors: ") ;
playerPick = scanner.nextInt() ;
// validation of the user's entry
if(playerPick < 1 || playerPick > 3)
System.out.println("Invalid entry! Try again.") ;
else
valid = true ;
}
computerPick = random.nextInt(3) + 1 ;
System.out.println("The computer picked " + computerPick) ;
// first we check if the computer and player did not pick the same thing
if(playerPick != computerPick)
{
if(playerPick == 1 && computerPick == 3) // check if the player picked rock(1) and the computer picked scissors(3)
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else if(playerPick == 3 && computerPick == 2) // check if the player picked scissors(3) and the computer picked paper(2)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else if(playerPick == 2 && computerPick == 1) // check if the player picked paper(2) and the computer picked rock(1)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else // otherwise, the computer has won this round
{
computerWinCount++ ;
System.out.println("Computer won!") ;
}
}
else
{
System.out.println("It's a tie!");
}
}
}
Let's go point by point.
You aren't taking the user input for determining the choice of playing in a while loop, so your game won't run more than once. You can take that input as:
while (true) {
System.out.println("Play again? Type yes or no.");
String YoN= input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
game():
} else {
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
break;
}
}
If user gives input other than yes, you're trying to print Cwin and Uwin, but you haven't declared those variables in the scope of main method. So your program won't compile anyways.
You can keep global variables in the class running main method.
public static int Cwin = 0;
public static int Uwin = 0;
Update
I've gone through your code and found a few more problems. As far as I understand, you want to receive choice input from user and validate it in this segment:
if (choice > 1 || choice < 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
Well, this condition doesn't supports what you've printed inside, this choice > 1 || choice < 3 condition always gets true. Also, you haven't prompted to take the entry from the user again.
You can fix this issue as below:
while (choice < 1 || choice > 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
choice = console.nextInt();
}
Then you're trying to make random choices for Computer. But you're selecting through upper bound and adding 1 to it. Why not set the bound to 1 more?
int comp = r.nextInt(4);
Then, finally, you're trying to compare the choice and the result. Where result was assigned -1 at the time of declaration and was never changed. That's why it'll never enter any if blocks and the Cwin and Uwin will always print 0. I bet you wanted comp here, in place of result. Also, I've tried to make the program more understandable to user while running.
if (choice == 1 && comp == 2) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 2 && comp == 3) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 3 && comp == 1) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 2 && comp == 1) {
Uwin++;
System.out.println("You win!");
return;
}
if (choice == 3 && comp == 2) {
Uwin++;
System.out.println("You win!");
return;
}
if (choice == 1 && comp == 3) {
Uwin++;
System.out.println("You win!");
return;
}
System.out.println("It's a draw!");
It will work as expected if you fix the aforementioned issues.
Note: I haven't refactored your code, I've just pointed out the problems and fixed it without modifying it much. It can be made lot more better than the current condition. Let's keep the topic for another day's question.
I modify your code somewhat.
You mention in a comment that you don't want to use an array and static variable.
so, I tried some different method hope It will help you.
It is fully working code
import java.util.*;
public class rockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome To Rock Paper scissors Game Type yes to continue or no for close.");
String YoN = input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
game();
} else if(YoN.equalsIgnoreCase("yes")) {
System.out.println("Thank You");
}else {
System.out.println("Enter valid input");
}
}
public static void game() {
int Uwin = 0;//user win count
int Cwin = 0;//computer win count
int tie = 0;//Tie count
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("Are you sure!!! Want to continue? Type yes or no.");
String YoN = input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
Scanner console = new Scanner(System.in);
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
int choice = console.nextInt();
int result = (int) (Math.random()*(3-1)) + 1;
if (choice < 1 || choice > 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
if((choice == 1 && result == 3) || (choice == 2 && result == 1) || (choice == 3 && result == 2)) {
System.out.println("Computer Choose"+result);
Uwin++;
}else if((choice == 1 && result == 2) || (choice == 2 && result == 3) || (choice == 3 && result == 1)) {
System.out.println("Computer Choose"+result
);
Cwin++;
}else {
System.out.println("Computer Choose"+result);
tie++;
}
} else if(YoN.equalsIgnoreCase("no")) {
System.out.println("Computer wins: " + Cwin + "\nUser wins: " + Uwin+"\nTie: "+tie);
System.out.println("Thank you");
break;
}else {
System.out.println("Enter valid input");
}
}
}
}
Track the score separately from the individual game
It looks you've written your game() method to play a single game of Rock, Paper, Scissors. In that case, you only need to return one value: who won that single game. Then your main method can keep track of the current scores and print out the totals after it's all done.
Consider an approach like the following:
import java.util.*;
public class rockPaperScissors {
public final static int USER_WON = 1; // Added these constants
public final static int COMPUTER_WON = 2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Uwin = 0;// user win count // Moved from `game()`
int Cwin = 0;// computer win count // Moved from `game()`
System.out.println("Play again? Type yes or no.");
String YoN = input.next();
if (YoN.equalsIgnoreCase("yes")) {
int winner = game(); // Modified this line
if (winner == USER_WON) { // Added this section
Uwin++;
} else {
Cwin++;
}
} else {
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
}
}
public static int game() { // Modified this line
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
Scanner console = new Scanner(System.in);
//// Truncating for brevity ////
if (choice == 3 && result == 1) {
return COMPUTER_WON; // Modified this line
}
if (choice == 2 && result == 1) {
return USER_WON; // Modified this line
}
//// Truncating for brevity ////
}
}
Notice that I moved the Uwin and Cwin variables out of game() and into your main method. Then I changed game() to return an integer instead of nothing (void) and replaced the Cwin++ and Uwin++ statements with a simple return COMPUTER_WON or return USER_WON based on the results of the rock, paper, scissors match. That return value can then be processed in your main method to keep a running total of how many games each player has won.
Use a class
If you're interested in trying something more advanced, consider creating an Object to encapsulate the two values you want to return.
For example, by storing both win counts in a simple Scoreboard object like the one below would enable you to return the two win counts at the same time and encapsulate the process of printing the scoreboard to the screen.
If you go this route, you'd have to make sure that all games reference the same Scoreboard. There are a variety of ways to do this from using a class variable, to passing the Scoreboard as a function parameter to the game() method, to moving all your logic for playing multiple games into the game() method. There are lots of options for you to try out and see which works best for you in this situation.
public class Scoreboard {
private int computerWins;
private int playerWins;
public Scoreboard() {
computerWins = 0;
playerWins = 0;
}
public void addComputerWin() {
computerWins++;
}
public void addPlayerWin() {
playerWins++;
}
#Override
public String toString() {
return "Scoreboard: "
+ "\n - Computer wins: " + computerWins
+ "\n - Player wins: " + playerWins;
}
}
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.
Sorry I am new to this site so not sure how this will show up. I am trying to make a simple Rock, Paper, Scissors game. After the while statement, if R, P, S isn't entered, the program just does nothing. I want it to loop back to the question at the beginning so a right choice can be entered. Also, how would I enter a print statement like "Invalid Choice Please Retry"?
package rps.gameapp;
import java.util.Scanner;
public class RPSGameApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int randNum = (int) (Math.random() * 3);
do
{
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));
String compChoice = "";
switch (randNum)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer entered \"" + compChoice + "\".");
if (compChoice.equalsIgnoreCase(userChoice))
{
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase(userChoice)
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P"))
{
System.out.println("User Wins");
} else
{
System.out.println("User Loses");
}
System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();
} while (playAgain.equalsIgnoreCase("Y"));
System.out.println("Thanks for Playing!");
}
}
It looks like you forgot one do for your inner do while loop.
It should be :
do {
do {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P") && !userChoice.equalsIgnoreCase("R") && !userChoice.equalsIgnoreCase("S"));
...
} while (playAgain.equalsIgnoreCase("Y"));
Without that inner do (and the curly braces surrounding that loop's body), the inner loop becomes a while loop with an empty body.
Like Eran said, you need to wrap your do-while loop in another loop, that will keep asking user for correct input. This is fully working code. One thing that could be better is the message after user inputs wrong letter.
Edit: also make sure you draw random number for every iteration.
Edit 2: to change the message depending on user input you can introduce a new variable that will keep the track of number of times you asked user for correct input. If it is 0- it means user is asked the first time and we should print "Welcome" message. It is anything other than 0- you need to ask the user for correct input. After every round we assign zero to the variable again and the cycle repeats. I have implemented this change in the code. Note that this variable can also be a boolean.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int iterationNumber;
while (true) {
iterationNumber = 0;
do {
if (iterationNumber == 0) {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
} else {
System.out.println("Please enter valid letter.");
System.out.println("Pick R, P, or S.");
}
iterationNumber++;
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));
String compChoice = "";
int randNum = (int) (Math.random() * 3);
switch (randNum) {
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer entered \"" + compChoice + "\".");
if (compChoice.equalsIgnoreCase(userChoice)) {
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase("R")
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P")) {
System.out.println("User Wins");
} else {
System.out.println("User Loses");
}
System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();
if (playAgain.equalsIgnoreCase("N")) {
break;
}
iterationNumber = 0;
}
System.out.println("Thanks for Playing!");
}
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;
}
}
So I made this rock paper scissors game a while ago using Java and I found a little bug I forgot to fix when I showed it to my friend today. Basically, the code takes a user input (i.e rock, paper, or scissors) and if their input does not equal rock, paper, or scissors, the main while loop is broken and the game is stopped.
How can I make it so that not only does it break the loop, but restarts it as well? I want to do this so that when someone gives an invalid input it automatically restarts so the player doesn't need to run the program all over again.
Here's the code for my main class:
public class rps {
public static void main(String []args){
boolean gameRunning = true;
while(gameRunning) {
System.out.println("Do you choose rock, paper, or scissors?");
UserChoice userInput = new UserChoice();
String userChoice = userInput.userDecide();
if(userChoice != "rock" || userChoice != "paper" || userChoice != "scissors") {
System.out.println("'" + userChoice + "'" + " is not a valid choice.");
System.out.println("Please choose between rock, paper, or scissors.");
gameRunning = false;
break;
// this is where I want to restart the function
}
System.out.println("You threw: " + userChoice);
ComputerInput computerChoice = new ComputerInput();
String computerInput = computerChoice.computerDecide();
System.out.println("Computer threw: " + computerInput);
CompareChoices compareResults = new CompareChoices();
gameRunning = compareResults.compare(userChoice, computerInput);
}
}
};
UPDATE
I figured out a few of the problems thanks to some help from the nice people on here. I used && instead of || (which is dumb because I originally used && anyways -_-), I used the "continue" statement instead of break, I removed gameRunning = false;, and I changed the way userChoice was compared to the valid responses.
Instead of comparing it to Strings like "rock" and "paper", I created an array
(String validChoices[] = {"rock", "paper", "scissors"};) which holds the valid responses. Then I compared userChoice to the indices of the array.
Here is my new code:
public class rps {
public static void main(String []args){
boolean gameRunning = true;
while(gameRunning) {
System.out.println("Do you choose rock, paper, or scissors?");
UserChoice userInput = new UserChoice();
String userChoice = userInput.userDecide();
String validChoices[] = {"rock", "paper", "scissors"};
if(!userChoice.equals(validChoices[0]) && !userChoice.equals(validChoices[1]) && !userChoice.equals(validChoices[2])) {
System.out.println("'" + userChoice + "'" + " is not a valid choice.");
System.out.println("Please choose either rock, paper, or scissors.");
continue;
}
System.out.println("You threw: " + userChoice);
ComputerInput computerChoice = new ComputerInput();
String computerInput = computerChoice.computerDecide();
System.out.println("Computer threw: " + computerInput);
CompareChoices compareResults = new CompareChoices();
gameRunning = compareResults.compare(userChoice, computerInput);
}
}
};
Thanks everyone!
Do not set gameRunning to false, to not use break, use continue, which will ignore the rest of the loop and start the loop again.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
A couple of problems. setting your loop condition to false and breaking leaves no way to restart the loop. Also, as #resueman hinted at. Use .equals() instead of == for comparing strings. My suggestion is to put the error checking inside another while loop.
while(!userChoice.equals("rock") && !userChoice.equals("paper") && !userChoice.equals("scissors")) {
System.out.println("Your choice was invalid, try again");
userChoice = userInput.userDecide();
}
Also, you should maybe declare some of this stuff outside your while loop (I am thinking of your ComputerInput, UserInput and CompareChoices objects).