the following is my code for a rock, paper, scissors game in BlueJ. When I compile and the user enters an input, the computer immediately prints numerous outputs from playerWins(). The game ends when the user types "quit". Could someone help me so my screen won't be flooded? (and if there is any way to condense my code that would also be great).
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors
{
public static void main(String[] args)
{
int wins = 0, losses = 0, ties = 0;
boolean output;
Scanner scan = new Scanner(System.in);
System.out.print("(R)ock, (P)aper, (S)cissors, or quit: ");
String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false)
{
playerChoice = playerChoice.toUpperCase();
String computerChoice = getComputerChoice();
if(playerChoice.equals(computerChoice) != true)
{
output = playerWins(playerChoice, computerChoice);
if (output == true)
{
wins++;
}
else if (output == false)
{
losses++;
}
}
else
{
ties++;
System.out.println("Tie!");
}
}
System.out.println("QUIT");
System.out.println("Wins: " + wins);
System.out.println("Losses: " + losses);
System.out.println("Ties: " + ties);
scan.close();
}
public static String getComputerChoice()
{
Random gen = new Random();
int num = gen.nextInt(30) + 1;
if (num % 3 == 2)
{
return "R";
}
else if (num % 3 == 1)
{
return "P";
}
else
{
return "S";
}
}
public static boolean playerWins(String playerChoice, String computerChoice)
{
if (playerChoice.equals("R") == true)
{
if (computerChoice.equals("P") == true)
{
System.out.println("My Point! \nP beats R"); // Rock is beaten by paper
return false;
}
else if (computerChoice.equals("S") == true)
{
System.out.println("Your Point! \nR beats S"); // Rock beats scissors
return true;
}
}
else if (playerChoice.equals("P") == true)
{
if (computerChoice.equals("R") == true)
{
System.out.println("Your Point! \nP beats R"); //Paper beats rock
return true;
}
else if (computerChoice.equals("S") == true)
{
System.out.println("My Point! \nS beats P"); //Paper is beaten by scissors
return false;
}
}
else if (playerChoice.equals("S") == true)
{
if (computerChoice.equals("P") == true)
{
System.out.println("Your Point! \nS beats P"); //Scissor beats paper
return true;
}
else if (computerChoice.equals("R") == true)
{
System.out.println("My Point! \nR beats S"); //Scissors is beaten by rock
return false;
}
}
return false;
}
}
These two lines are the problem:
String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false) {
You are reading one line and then checking that line over and over again. You need to read a new line inside the loop. The way you have it now, it is just trying to make the same move over and over infinite times.
Try:
String playerChoice = scan.nextLine();
while (playerChoice.equals("quit") == false) {
//do all of the stuff that is already inside your loop
playerChoice = scan.nextLine();
}
This will get user input again every time after processing the last input.
You are checking the user-input only once, that is before the loop:
String playerChoice = scan.nextLine();
One very nice method to solve that is the following:
String playerChoice;
while((playerChoice = scan.nextLine()).equals("quit") == false)
{
//more code
}
What the above code does, is that playerChoice is set right before .equals("quit") is called. If you use this method you don't need one more line at the end of your loop to set playerChoice but just do that in the head of your loop.
Related
I'm trying to start the game over if the user enters "Yes". I tried using a while loop, but it's gone wrong somewhere that I can't find.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
int playerScore = 0;
int computerScore = 0;
int round = 0;
String decision;
// Get user input
while (round<3) {
System.out.println("Please enter your move: Rock, Paper or Scissors");
System.out.println(">>");
Scanner input = new Scanner(System.in);
String playerMove = input.next();
// Check if user input is valid
if (!playerMove.equalsIgnoreCase("Rock") && !playerMove.equalsIgnoreCase("Paper") && !playerMove.equalsIgnoreCase("Scissors")) {
System.out.println("Move is invalid, Opponent gets a point");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else {
// Randomly generate computerMove
int computerInt = (int)(Math.random()*3);
String computerMove = " ";
if (computerInt == 0) {
computerMove = "Rock";
} else if (computerInt == 1) {
computerMove = "Paper";
} else if (computerInt == 2) {
computerMove = "Scissors";}
System.out.println("Opponent move is "+ computerMove);
// Establish winning or losing scenarios
if (playerMove.equalsIgnoreCase(computerMove)) {
System.out.println("Tied");
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else if (playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Scissors") ||
playerMove.equalsIgnoreCase("Scissors") && computerMove.equalsIgnoreCase("Paper") ||
playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Paper")) {
System.out.println("You won");
playerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
else {
System.out.println("You lost");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
}
// Determine the last winner
if (playerScore < computerScore) {
System.out.println("You lose, so sad ;(");
} else if (playerScore > computerScore) {
System.out.println("You win, here's a cookie ;) ");
} else {
System.out.println("Tied, maybe try harder ^_^"); }
}
System.out.println("Do you wanna play again?");
}
}
}
Sounds like this might be a HW or Test question, so just writing steps to help you out:
first have a user-decision variable and initialize it to "Y"
then put the game in a while(user-decision="Y") loop
at the end of this loop ask the user for their decision and update the user-decision variable to either Y or N
if they say Y loop continues, else it ends
if you need to repeat your code, put it in a new class (Game) and instantiate in main () and call until your Game class returns TRUE (press Y)
package appMain;
import java.util.Scanner;
public class Game {
public Boolean PlayGame() {
System.out.println("START GAME");
//
// >> PUT THERE YOUT GAME CODE <<
//
Scanner input = new Scanner(System.in);
String answer = input.next();
if(answer.equals("Y")) {
return true;
}
return false;
}
}
package appMain;
public class GameMain {
public static void main(String args[]) {
Game game = new Game();
while (game.PlayGame()) {
}
System.out.println("GAME finish");
}
}
I've written out all the code for an assignment for my programming class. The assignment requires us to create a program that allows the user to play rock paper scissors against a computer. We're required to have individual methods to obtain the computer's choice, the user's choice, check if the user's choice is valid, and also to determine the winner of the match. If a match doesn't end in a tie we need to print why the match was won, eg. "Scissors cuts Paper," and print who wins. Everything works properly, except when the user wins it's never counted or announced. For example instead of printing:
The computer's choice was rock. The user's choice was paper. Paper covers Rock. The user wins!
it prints:
The computer's choice was rock. The user's choice was paper. Paper covers Rock.
import java.util.Scanner;
import java.util.Random;
public class FinalRockPaperScissors {
//Computer's Choice
public static int computersChoice (int options) {
Random randGen = new Random();
int computerValue = randGen.nextInt(options)+1;
System.out.println(computerValue); //FOR TESTING ONLY
return computerValue;
}
//Player's Choice
public static int usersChoice () {
Scanner scnr = new Scanner(System.in);
System.out.print("Enter 1 for rock, 2 for paper, or 3 for scissors: ");
int userValue = scnr.nextInt();
if (isValid(userValue) == true) {
return userValue;
}
else {
userValue = 0;
return userValue;
}
}
//Check for valid user input
public static boolean isValid (int userInput){
if (userInput == 1 || userInput == 2 || userInput == 3) {
return true;
}
else {
return false;
}
}
//Checking winner
public static char determineWinner () {
char win;
int computerValue = computersChoice(3);
int userValue = usersChoice();
//print computer choices
if (computerValue == 1) {
System.out.println("The computer's choice was rock.");
}
else if (computerValue == 2) {
System.out.println("The computer's choice was paper.");
}
else if (computerValue == 3){
System.out.println("The computer's choice was scissors.");
}
//print user choices
if (userValue == 1) {
System.out.println("The user's choice was rock.");
}
else if (userValue == 2) {
System.out.println("The user's choice was paper.");
}
else if (userValue == 3){
System.out.println("The user's choice was scissors.");
}
//check who won
if (computerValue == 1) { //rock vs
if (userValue == 2) { //paper
System.out.println("Paper wraps Rock.");
return win = 'b';
}
else if (userValue == 3) { //scissors
System.out.println("Rock smashes Scissors.");
return win = 'a';
}
else if (userValue == 1){ //rock
return win = 'c';
}
else {
System.out.println("The user chose an invalid number. This round will be ignored.");
return win = 'd';
}
}
else if (computerValue == 2) { //paper vs
if (userValue == 2) { //paper
return win = 'c';
}
else if (userValue == 3) { //scissors
System.out.println("Scissors cuts Paper.");
return win = 'b';
}
else if (userValue == 1){ //rock
System.out.println("Paper wraps Rock.");
return win = 'a';
}
else {
System.out.println("The user chose an invalid number. This round will be ignored.");
return win = 'd';
}
}
else { //scissors vs
if (userValue == 2) { //paper
System.out.println("Scissors cuts Paper.");
return win = 'a';
}
else if (userValue == 3) { //scissors
return win = 'c';
}
else if (userValue == 1){ //rock
System.out.println("Rock smashes Scissors.");
return win = 'b';
}
else {
System.out.println("The user chose an invalid number. This round will be ignored.");
return win = 'd';
}
}
}
public static void main(String[] args) {
int userWins = 0;
int computerWins = 0;
int ties = 0;
int error = 0;
//for (int i = 0; i < 1; i++) { //5 for testing purposes
if (determineWinner() == 'a') {
System.out.println("The computer wins!");
System.out.println("");
computerWins++;
}
else if (determineWinner() == 'b') {
System.out.println("The user wins!");
System.out.println("");
userWins++;
}
else if (determineWinner() == 'c'){
System.out.println("The game is tied!");
System.out.println("");
ties++;
}
else {
error++;
}
//}
System.out.println("The number of ties is " + ties);
System.out.println("The number of user wins is " + userWins);
System.out.println("The number of computer wins is " + computerWins);
//output final winner
if (computerWins > userWins) {
System.out.println("Computer is the winner.");
}
else if (userWins > computerWins) {
System.out.println("User is the winner.");
}
else {
if (userWins == computerWins) {
System.out.println("User is the winner.");
}
else if (computerWins == ties) {
System.out.println("Computer is the winner.");
}
}
}
}
After some testing I've discovered that the problem may be with my userchoice() method. If I disable this method and give a set value for the user, everything works as it should. The problem is I don't know why it doesn't work, and as a result I can't fix it.
I think you're so new to Java and also let's start to show you your mistake in this code, you called determineWinner() multiple times which shouldn't be like that because you repeat the game four times to determine the result once, so you should call it once and get the returned value and check the value, like:-
char result = determineWinner(); //Play the game and get the result
// use it in conditions
if (result == 'a') {
System.out.println("The computer wins!");
System.out.println("");
computerWins++;
}
else if (result == 'b') {
System.out.println("The user wins!");
System.out.println("");
userWins++;
}
else if (result == 'c'){
System.out.println("The game is tied!");
System.out.println("");
ties++;
}
else {
error++;
}
In your main function You are calling determineWinner() every time you test your if condition. The proper way would be to store the returned value in a variable and then check if that variable is 'a', 'b' or 'c'. For example:
char result = determineWinner();
if (result == 'a') {
System.out.println("The computer wins!");
System.out.println("");
computerWins++;
}
The errors I am getting are "answer cannot be resolved". 1/4th of the way down the page. Looked online still don't see what it should be. Would it be easier to use the while loop instead? skipping the do loop completely?
import java.util.Scanner;
public class RPSS{
//Main method
public static void main(String[ ] argc)
{
Scanner tnt = new Scanner(System.in);
String computerHand; // string variable for computer choice
String userHand; // string variable for user choice
// do loop begining
do
{
computerHand = computerHand();
userHand = userHand();
String winner = getWinner(computerHand, userHand);
System.out.println(winner);
System.out.print("User picks" + userHand );
System.out.println("Computer picks " + computerHand );
System.out.println("play again?");
String answer = tnt.next();
//Condition for the do-while loop HERE IS THE ERROR LOCATION
}while (!answer.Equals("No") && (!answer.Equals("no"))); //condition for while loop
String answer = tnt.next();
}
public static String userHand(){ //method for users choice in the game
//prints message to user giving them choices
System.out.println("Lets play rock paper scissors");
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 master choice
}
public static String computerHand() //method for computer generated choice
{
int computernum = (int)(Math.random() * (( 3) + 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="";
System.out.println( " the comp chose" + computerChoice);
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println("The computer"); }
else if (userChoice.equals("Paper") && computerChoice.equals("Scissors")){
System.out.println(" The computer wins");
}
else if (userChoice.equals("Scissors") && computerChoice.equals("Rock")){
System.out.println(" The computer wins ");
}
else if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println(" The computer wins ");
}
if (userChoice.equals(computerChoice))
{
System.out.println(" There is no winner");
}
return winner;
}
}
Use tnt.next() which returns the next string. there is no such thing as nextString().
Also, add return winner; at the end of getwinner method.
You declared answer inside the braces of your do and then tried to use it outside the braces. Once you left the braces, the variable was out of scope.
Alright, I have a class assignment to create 3 predetermined methods for a rock, paper, scissors program written by the teacher. However, when I run the program it running the methods multiple times in a row. I've looked through the code several times and can't figure out the problem.
Below is the teacher provided portion of the program:
public class Game
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
RockPaperScissors rps = new RockPaperScissors (); //***Your class
int numGames = 0;
String userChoice = "";
String cpuChoice = "";
String winner = "";
int userWins = 0;
int cpuWins = 0;
System.out.println("Welcome to Rock, Paper, Scissors!\n");
//Get odd number of games
System.out.println("How many rounds would you like to play?");
numGames = in.nextInt();
while (numGames % 2 == 0) //Even number
{
System.out.println("Sorry, number of games must be odd. Please try again:");
numGames = in.nextInt();
}
//Flush the buffer
in.nextLine();
//Play the game for the number of rounds the user entered
for (int i = 1; i <= numGames; i++)
{
//Get the user and computer choices
userChoice = rps.getUserChoice(); //***Your method
cpuChoice = rps.getCPUChoice(); //***Your method
System.out.println("Computer chooses " + cpuChoice);
//Pick winner
winner = rps.pickWinner(userChoice, cpuChoice); //***Your method
if (winner.equalsIgnoreCase("Tie"))
{
System.out.println("It's a tie! Play again.");
numGames++;
}
else
{
if (winner.equalsIgnoreCase("User"))
{
userWins++;
}
else if (winner.equalsIgnoreCase("Computer"))
{
cpuWins++;
}
else
{
System.out.println("Error in picking winner");
}
System.out.println(winner + " wins!");
}
} //end for
//Print results
System.out.println("\nUser wins: " + userWins);
System.out.println("Computer wins: " + cpuWins);
if (userWins > cpuWins)
{
System.out.println("\nThe user won!");
}
if (cpuWins > userWins)
{
System.out.println("The computer won!");
}
//Close game
System.out.println("\nThank you for playing!");
} //end main
} //end class
And here is my code which I'm assuming where the problem is coming from:
public class RockPaperScissors {
public String getUserChoice() {
Scanner sc = new Scanner (System.in);
System.out.println("Enter your choice:");
String userInput = sc.nextLine();
boolean end = true;
while (end == true){
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
end = false;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
userInput = sc.next();
}
}
return userInput;
}// end getUsechoice
public String getCPUChoice() {
String computerChoice = " ";
Random rand = new Random();
int randomNum = rand.nextInt(3) + 1;
if (randomNum == 1){
computerChoice = "rock";
}
else if (randomNum == 2){
computerChoice = "paper";
}
else if (randomNum == 3){
computerChoice = "scissors";
}
return computerChoice;
}
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (getUserChoice().equalsIgnoreCase("rock")) {
if (getCPUChoice().equalsIgnoreCase("rock")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("paper")){
result = "Computer";
}
else if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (getUserChoice().equalsIgnoreCase("paper")){
if (getCPUChoice().equalsIgnoreCase("paper")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("rock")){
result = "User";
}
else if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (getUserChoice().equalsIgnoreCase("Scissors")){
if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("rock")){
result = "Computer";
}
else if (getCPUChoice().equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
}//end pickWinner
}//end rockPaperScissors
Here would be a sample session of the program:
Welcome to Rock, Paper, Scissors!
How many rounds would you like to play? 1 Enter your choice: rock
Computer chooses paper Enter your choice: rock Enter your choice: rock
Computer wins!
User wins: 0 Computer wins: 1 The computer won!
Thank you for playing!
Here I'm wondering why it continues asking for user input multiple times. Also it runs the other methods as well which is why the computer won despite picking paper vs rock.
Alright added in the final changes to my program and it's working perfectly now:
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (userChoice.equalsIgnoreCase("rock")) {
if (cpuChoice.equalsIgnoreCase("rock")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("paper")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (userChoice.equalsIgnoreCase("paper")){
if (cpuChoice.equalsIgnoreCase("paper")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "User";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (userChoice.equalsIgnoreCase("Scissors")){
if (cpuChoice.equalsIgnoreCase("scissors")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
}//end pickWinner
The problem seems to be that when I called in getCPUChoice or getUserChoice it would rerun the program and then change the final answers.
You calling getUserChoice() in the pickWinner method. It should be the userChoice method parameter you should be checking.
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (userChoice.equalsIgnoreCase("rock")) {
if (cpuChoice.equalsIgnoreCase("rock")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("paper")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (userChoice.equalsIgnoreCase("paper")){
if (cpuChoice.equalsIgnoreCase("paper")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "User";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (userChoice.equalsIgnoreCase("Scissors")){
if (cpuChoice.equalsIgnoreCase("scissors")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
You should ask for user input in each loop and not just once.
public class RockPaperScissors {
public String getUserChoice() {
Scanner sc = new Scanner (System.in);
System.out.println("Enter your choice:");
//not here
String userInput;
while (true){
//this is the right place
userInput = sc.nextLine();
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
break;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
}
}
return userInput;
}// end getUsechoice
//...
}//end rockPaperScissors
try changing this in your else part
userInput = sc.next();
to this
userInput = sc.nextLine();
So it will go to next line
So the resulting code ll be
while (end == true){
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
end = false;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
userInput = sc.nextLine();
}
}
First off, I'm pretty green when it comes to java. So, I'm making a rock paper scissors game with 2 classes and an object connecting the two. For some unknown reason, when I use the object, it cannot find the method im pointing to. The error is "cannot find symbol" and is in the first class where it is game.RockPaperScissors();
public class RPSRunner {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
char response;
//add in a do while loop after you get the basics up and running
out.print("type in your prompt [R,P,S] :: ");
String player = keyboard.nextLine();
RockPaperScissors game = new RockPaperScissors();
do {
game. **RockPaperScissor **(player);
} while (player == r || p || s);
}
}
and
public class RockPaperScissors {
String playChoice;
String compChoice;
Random random = new Random();
int rand = 0;
public RockPaperScissors() {
playChoice = " ";
compChoice = " ";
}
public RockPaperScissors(String player) {
setPlayers(player);
}
public void setPlayers(String player) {
playChoice = player;
rand = random.nextInt(3);
if (rand == 0) {
compChoice = "r";
}
if (rand == 1) {
compChoice = "p";
}
if (rand == 2) {
compChoice = "s";
}
System.out.println("player had " + playChoice);
System.out.println("computer had " + compChoice);
}
public String determineWinner() {
String winner = "";
if ((compChoice == "r") && (playChoice == "p")) ;
{
winner = "!Player wins << Paper covers Rock>>!";
}
if ((compChoice == "r") && (playChoice == "s")) ;
{
winner = "! Computer wins << Rock breaks Scissors >>!";
}
if ((compChoice == "p") && (playChoice == "r")) ;
{
winner = "! Computer wins << Paper covers Rock>>!";
}
if ((compChoice == "p") && (playChoice == "s")) ;
{
winner = "!Player wins << Scissors cuts paper >>!";
}
if ((compChoice == "s") && (playChoice == "p")) ;
{
winner = "! Computer wins << Scissors cuts paper >>!";
}
if ((compChoice == "s") && (playChoice == "r")) ;
{
winner = "!Player wins << Rock breaks Scissors >>!";
}
if (compChoice == playChoice) ;
{
winner = " !Tie << Both the computer and player have selected " + compChoice + " >>!";
}
return winner;
}
public String toString() {
String output = "";
return output;
}
}
Change
public RockPaperScissors(String player)
To
public void RockPaperScissors(String player)
The former is a constructor while the latter is a method. Also,there seems to be numerous other problems in your code(like the condition of the do...while loop,using == to compare Strings etc)