Rock, paper, scissors game Invalid entry loop - java

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.

Related

Having to resubmit user choice over and over

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!

Java rock paper scissor printing the statements oddly

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 "

Java Do While isn't working properly

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!");
}

A way to reset program on cmd?

I wrote a simlpe dice game and would like to know a way to reset the program after typing something like "Reset". I use cmd to run my programs. There is no graphics included in any of my programs whatsoever.
import java.util.Scanner;
import java.util.Random;
public class Dice
{
public static void main(String[] args)
{
String personPlay; //User's play
String computerPlay = ""; //Computer's play
int computerInt; //Randomly generated number used to determine computer's play
String response;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
System.out.println("Let's play some dice!");
//Generate computer's play
computerInt = generator.nextInt(6)+1;
//Translate computer's randomly generated play to
//string using if statements
if (computerInt == 1)
computerPlay = "1";
else if (computerInt == 2)
computerPlay = "2";
else if (computerInt == 3)
computerPlay = "3";
else if (computerInt == 4)
computerPlay = "4";
else if (computerInt == 5)
computerPlay = "5";
else if (computerInt == 6)
computerPlay = "6";
//Get player's play from input
System.out.println("Choose a number between 1 and 6.");
personPlay = scan.next();
//Print computer's play
System.out.println("The dice rolled " + computerPlay);
//See if you won.
if (personPlay.equals(computerPlay))
System.out.println("You won!");
else System.out.println("You lost!");
}
}
You should use an infinite loop and get input from user, check if user entered "RESET", if so roll the dice again or do whatever you're doing now.
If he entered a phrase like "EXIT" infinite loop ends or your program ends.
Usually I don't like giving full answers, but there are some improvements I wanted to show and just listing them would be a lot of work as well.
import java.util.Scanner;
import java.util.Random;
public class Dice
{
private static void play(Scanner scan, Random generator)
{
int computersPlay, usersPlay;
System.out.println("Let's play some dice!");
computersPlay = generator.nextInt(6) + 1;
System.out.print("Give a number:");
usersPlay = scan.nextInt();
System.out.printf("The dice rolled %d\n", computerPlay);
if (computersPlay == usersPlay) {
System.out.println("You win !");
}
else {
System.out.println("You lose!");
}
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Random generator = new Random();
do {
play(scan, generator);
System.out.println("If you want to continue type:'Reset'");
} while(scan.next().equals("Reset");
}
}
Changes moving the play to a different method to keep oversight, using the Scanners nextInt method to obtain a number directly and compare that instead, and the do {} while(); statement to let it repeat an arbitrary amount of times (given that you type reset)
By "reset" I assume you meant "repeat"? Use a while loop.
Also, no real need to store String values other than capture what the user entered.
public class DiceGuess {
// Global variables for this class
static Random generator = new Random();
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Let's play some dice!");
// Initialize some variables
int computerInt;
String response;
while (true) { // Play forever
computerInt = generator.nextInt(6) + 1;
System.out.println("Choose a number between 1 and 6. ('quit' to stop playing)");
response = scan.nextLine();
if (response.equalsIgnoreCase("quit")) break; // Stop the game
try {
System.out.println("The dice rolled " + computerInt);
if (Integer.parseInt(response) == computerInt) {
System.out.println("You won!");
} else {
System.out.println("You lost!");
}
} catch (NumberFormatException e) {
System.err.println("That wasn't a number!");
}
}
}
}

Java SecretWord Code

I am making basic java program to hold a secret word (mouse) and allow a user to guess letters. The program will end either when the user guesses all the letters in the word, or when they guess 7 wrong letters. Whenever I type any letter into the program, it will run through it without giving the user an option to enter another letter. What should I add so that it will only run the program once per letter entered? Also if it wasnt quite obvious I am new to coding.
import java.util.Scanner;
public class GuessWord
{
String Secretword="mouse";
String letter;
int index;
private int number;
private int counter;
private String guesses;
Scanner scan = new Scanner(System.in);
public GuessWord()
{
String Secretword="";
String letter = "";
String guesses = "";
int number = 0;
int counter = 0;
int index = 0;
}
public String getLetter(){
System.out.println("Please enter a letter");
letter = scan.next();
return letter;
}
public void calc(){
guesses=letter;
while(number <= 7 && counter<5)
{
if(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
guesses=guesses+" " +letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if(number == 7){
System.out.println("You lose");
}else
{
System.out.println("You win");
}
}
}//class
public class GuessWordR
{
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
g1.getLetter();
g1.calc();
}//class
}//main
You should use a while loop.
So while some condition is not met keep asking the user to enter a new key.
Perhaps add a new method to the GuessWord Class
public void startGuessing() {
while(hasGuesses /* some boolean flag */) {
getLetter()
getCalc()
}
}
And then call that method in your main method instead of getLetter() and getCalc().
You will need to add a boolean variable to your class to indicate when to exit this while loop and the logic to keep count of the number of failed guesses etc.
Use a boolean flag and run it in a loop. but for that you need to restructure your code as well. First fix the calc() method
public boolean calc() {
guesses = letter;
if (number <= 7 && counter < 5) {
if (Secretword.indexOf(letter) != -1) {
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
} else {
System.out.println("You entered an incorrect letter");
number++;
}
guesses = guesses + " " + letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if (number == 7) {
System.out.println("You lose");
return true;
} else if (counter == 5) {
System.out.println("You win");
return true;
} else {
return false;
}
}
Your main method should be update like this
public static void main(String[] args) {
GuessWord g1 = new GuessWord();
boolean completed = false;
while (!completed) {
g1.letter = g1.getLetter();
completed = g1.calc();
}
}
you ask user for input unless condition get satisfied instead of asking and calculating once. And read char by char input instead of reading whole string.
something like:
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
while(number <= 7 && counter<5){
g1.getLetter();
g1.calc();
}
}//class

Categories