Rock Paper Scissors. Java. Methods - java

I'm assuming this is a logical error. I can't get the results to add up and I can't get the right results. Every time I enter either rock, paper, scissors, it then decides from there if I've won, lost, or tied. What is wrong with my code?
public class RockPaperScissors {
public static void displayGreeting()
{
String intro = "This program is a game. A game of Rock, Paper, Scissors\n"+
"It is you against the computer. Rock beats scissors, Paper\n"+
" beats rock, and scissors beats paper. Good luck and may the\n"+
"odds be ever in your favor.";
JOptionPane.showMessageDialog(null, intro, "Rock Paper Scissors",1);
}
public static String generateComputersChoice()
{
Random randomGenrator = new Random();
int randomNumber = randomGenrator.nextInt(3);
String weapon = "nothing";
switch(randomNumber){
case 0: weapon = "rock";
break;
case 1: weapon = "paper";
break;
case 2: weapon = "scissors";
break;
}
return weapon;
}
public static String enterPlayersChoice(){
String prompt = "You have a choice of picking rock, paper, or scissors.\n"+
"Choose wisely.";
String input = "";
input = JOptionPane.showInputDialog(null,prompt,"Choose your weapon",1);
String inputLower = input.toLowerCase();
return inputLower;
}
public static void main(String[] args)
{
displayGreeting();
// generateComputersChoice();
//enterPlayersChoice();
// JOptionPane.showMessageDialog(null,generateComputersChoice()+ enterPlayersChoice(5));
String player = enterPlayersChoice();
String comp = generateComputersChoice();
int ties = 0;
int playerWins = 0;
int compWins = 0;
for(int i = 0; i < 3; i ++){
//enterPlayersChoice(); //method
//generateComputersChoice(); //method
//JOptionPane.showMessageDialog(null,generateComputersChoice()+ enterPlayersChoice(1));
//System.out.println(player+ " " + comp);
//JOptionPane.showMessageDialog(null,player+ " " +comp);
if(player.equals(comp)){
JOptionPane.showMessageDialog(null, "It's a tie!");
ties ++;
}
else if(player.equals("rock")){
if(comp.equals("scissors")){
JOptionPane.showMessageDialog(null, "You win!");
playerWins ++;
}
}else if(comp.equals("rock")){
if(player.equals("scissors")){
JOptionPane.showMessageDialog(null, "You lose!");
compWins ++;
}
}else if(player.equals("scissors")){
if(comp.equals("paper")){
JOptionPane.showMessageDialog(null, "You win!");
playerWins ++;
}
}else if(comp.equals("scissors")){
if(player.equals("paper")){
JOptionPane.showMessageDialog(null, "You lose");
compWins ++;
}
}else if(player.equals("paper")){
if(comp.equals("rock")){
JOptionPane.showMessageDialog(null, "You Win!");
playerWins ++;
}
}else if(comp.equals("paper")){
if(player.equals("rock")){
JOptionPane.showMessageDialog(null, "You lose!");
compWins ++;
}
}else{
JOptionPane.showMessageDialog(null, "Invalid user input");
i--;
}
}
//Results
JOptionPane.showMessageDialog(null,"Here are the results\n\n"+
"\nTies: " +ties+
"\nComputer Wins: " +compWins+
"\nPlayer Wins: " + playerWins+
"\n\n Program Terminating", "Results",1);
}
}

Then it decides whether I've won, tied or lost but it won't
"reiterate" after that. After that it just says i've either won, lost,
or tied 3 times in a row
What you're actually doing is asking the input one time and then run the loop, so obviously you'll get the same result 3 times.
You need to ask at each iteration the user input :
String player;
String comp;
int ties = 0;
int playerWins = 0;
int compWins = 0;
for(int i = 0; i < 3; i ++){
player = enterPlayersChoice();
comp = generateComputersChoice();
/**/
}

First, you must get the player's choice and the computer's choice each loop. Move
String player = enterPlayersChoice();
String comp = generateComputersChoice();
inside the for loop at the start.
Also, if you say
else if(player.equals("rock")){
if(comp.equals("scissors")){
JOptionPane.showMessageDialog(null, "You win!");
playerWins ++;
}
Then the else if block will match when the player chooses "rock" regardless of the computer's choice. Then, if the computer doesn't choose "scissors", nothing will happen.
You need both conditions to match for this scenario to execute, else the first condition will match but the second might not, and nothing will happen. Try
else if (player.equals("rock") && comp.equals("scissors")){
and likewise for the other conditions.

you have regenerate the the user and computer's choices each time through the loop.
move
String player = enterPlayersChoice();
String comp = generateComputersChoice();
into the loop else it will be the same all 3 times

Related

How can I start the program over again

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

OverLoading Methods Var cannot be resolved.

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.

Rock Paper Scissors Difficulty Java

Im trying to make a rock, paper, scissors game where you choose 1,2 or 3 for rock then displays what you've chosen and what the computer has chosen. I then need to keep track of score for wins and at the end of every round ask the user if they want to play again.
import java.util.Scanner;
public class Rock5
{
//-----------------------------------------------------------------
// Plays the Rock-Paper-Scissors game with the user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int OPTIONS = 3;
final int ROCK = 1, PAPER = 2, SCISSORS = 3;
final int COMPUTER = 1, PLAYER = 2, TIE = 3;
int computer, player, winner = 0;
int wins = 0, losses = 0, ties = 0;
String again;
Scanner in = new Scanner(System.in);
do
{
computer = (int) (Math.random() * OPTIONS) + 1;
System.out.println();
System.out.print ("Enter your choice - 1 for Rock, 2 for " +
"Paper, and 3 for Scissors: ");
player = in.nextInt();
System.out.print ("My choice was ");
// Determine the winner
switch (computer)
{
case ROCK:
System.out.println ("Rock.");
if (player == SCISSORS)
winner = COMPUTER;
else
if (player == PAPER)
winner = PLAYER;
else
winner = TIE;
break;
case PAPER:
System.out.println ("Paper.");
if (player == ROCK)
winner = COMPUTER;
else
if (player == SCISSORS)
winner = PLAYER;
else
winner = TIE;
break;
case SCISSORS:
System.out.println ("Scissors.");
if (player == PAPER)
winner = COMPUTER;
else
if (player == ROCK)
winner = PLAYER;
else
winner = TIE;
}
// Print results and increment appropriate counter
if (winner == COMPUTER)
{
System.out.println ("I win!");
losses++;
}
else
if (winner == PLAYER)
{
System.out.println ("You win!");
wins++;
}
else
{
System.out.println ("We tied!");
ties++;
}
System.out.println();
System.out.print ("Play again (y/n)?: ");
again = in.nextLine();
}
while (again.equalsIgnoreCase ("y"));
// Print final results
System.out.println();
System.out.println ("You won " + wins + " times.");
System.out.println ("You lost " + losses + " times.");
System.out.println ("We tied " + ties + " times.");
}
}
Use
player = Integer.valueOf(in.nextLine());
Instead of
player = in.nextInt();
and it'll work, because if not, the number you enter goes into player, and the \n characater goes into again = in.nextLine() and because it's different of y it stops.

I can't get my rock, paper, scissors program to read the correct results

Whenever I run it, it seems that the loop to continue playing works, but the game outcome is not outputting correctly whenever the conputerChoose executes the randomGenerator. Please help. I'm new to java, and we are only suppose to use 3 methods - instructions, playGame and computerChoose. We are also suppose to use a user controlled loop to continue working. I can't seem to get this right and I still have to add a loop to count the number of time sthe game has been played, the number of times won and the number of times the computer won.
import java.util.*;
public class PRS {
public static Scanner kbd = new Scanner(System.in);
public static void instructions() {
System.out.println("\nThis is the popular game of paper, rock, scissors. Enter your"
+ "\nchoice by typing the word \"paper\", the word \"rock\" or the word"
+ "\n\"scissors\". The computer will also make a choice from the three"
+ "\noptions. After you have entered your choice, the winner of the"
+ "\ngame will be determined according to the following rules:"
+ "\n\nPaper wraps rock (paper wins)"
+ "\nRock breaks scissors (rock wins)"
+ "\nScissors cuts paper (scissors wins)"
+ "\n\nIf both you and the computer enter the same choice, then the game "
+ "\nis tied.\n");
}
public static int playGame(){
int outcome = 0;
System.out.print("Enter your choice: ");
kbd = new Scanner(System.in);
String player = kbd.nextLine().toLowerCase();
String computerChoice = computerChoose();
System.out.println("\nYou entered: " + player);
System.out.println("Computer Chose: " + computerChoose());
if(player.equals(computerChoose())){
outcome = 3;
}
else if (player.equals("paper") && computerChoice.equals("rock")){
outcome = 1;
}
else if (computerChoice.equals("paper") && player.equals("rock")){
outcome = 2;
}
else if (player.equals("rock") && computerChoice.equals("scissors")){
outcome = 1;
}
else if (computerChoice.equals("rock") && player.equals("scissors")){
outcome = 2;
}
else if (player.equals("scissors") && computerChoice.equals("paper") ){
outcome = 1;
}
else if (computerChoice.equals("scissors") && player.equals("paper")){
outcome = 2;
}
else if (player.equals("rock") && computerChoice.equals("paper") ){
outcome = 2;
}
else if (computerChoice.equals("rock") && player.equals("paper")){
outcome = 1;
}
return outcome;
}
public static String computerChoose(){
/*return "scissors";*/
Random generator = new Random();
String [] answer = new String [3];
answer [0]= "paper";
answer [1] = "rock";
answer [2] = "scissors";
return answer[generator.nextInt(3)];
}
public static void main(String[] args) {
kbd = new Scanner(System.in);
System.out.println("THE GAME OF PAPER, ROCK, SCISSORS:");
System.out.print("\nDo you need instructions (Y or N)? ");
String userPlay = kbd.nextLine();
if (userPlay.equalsIgnoreCase("y")){
instructions();
}
String answer;
do{
int result = playGame();
System.out.println(result);
switch (result){
case 1:
System.out.println("YOU WIN!");
break;
case 2:
System.out.println("Comp WINs!");
break;
case 3:
System.out.println("IT'S A TIE!");
break;
default:
}
System.out.print("\nPlay again ( Y or N)? ");
answer = kbd.nextLine();
}while(answer.equalsIgnoreCase("y"));
}
}
The first thing you need to do is only call computerChoose() once. Every time you are calling this method it is generating a new random number and hence a different answer. You should only call it once inside playGame() and assign it to a local variable.
E.g.
String computerChoice = computerChoose();
Then replace all of your other calls to computerChoose() with this variable name. This way you will display the one value and compare only the one value in your logic.
As for tracking other information such as the number of games, and the number of wins/losses, think about declaring a few more class variables (or local variables in the main method) which you can then assign, increment and read. You can do all this from within your do-while loop in the main method. No need for any additional loops.
In addition to Adam's answer, changing the do-while loop at the end to the following will resolve a few different issues.
String answer;
int winCount=0, lossCount=0, tieCount=0;
do{
int result = playGame();
switch (result){
case 1:
System.out.println("YOU WIN!");
winCount++;
break;
case 2:
System.out.println("Comp WINs!");
lossCount++;
break;
case 3:
System.out.println("IT'S A TIE!");
tieCount++;
break;
default:
}
System.out.print("\nPlay again ( Y or N)? ");
answer = kbd.nextLine();
}while(answer.equalsIgnoreCase("y"));
System.out.printf("Wins: %d, Losses: %d, Total plays: %d%n", winCount, lossCount, winCount+lossCount+tieCount);
You need to update result inside the while loop or else only the first game's results will be accurate.

Rock paper scissors, play again?

For my assignment I'm supposed make the program rock paper scissors which I figured that out my main problem is I can't get the program to play again right or get the program to calculate the game scores correctly pleas help I'm going crazy trying to figure this out?!
//Tayler Dorsey
import java.util.Random;
import java.util.Scanner;
public class PRS {
static Scanner keyboard = new Scanner(System. in );
public static void instructions() {
System.out.println("This is the popular game of paper, rock, scissors. Enter your\nchoice by typing the word \"paper\", the word \"rock\" or the word\n\"scissors\". The computer will also make a choice from the three\noptions. After you have entered your choice, the winner of the\ngame will be determined according to the following rules:");
System.out.println("Paper wraps rock (paper wins)\nRock breaks scissors (rock wins)\nScissors cuts paper (scissors wins)");
System.out.println("If both you and the computer enter the same choice, then the game is tied.");
}
public static int playGame() {
int ties = 0, wins = 0, losts = 0;
String userchoice, computerchoice;
System.out.println("Enter your choice: ");
userchoice = keyboard.next();
computerchoice = computerChoose();
System.out.println("You entered: " + userchoice);
System.out.println("Computer choose: " + computerchoice);
if ((userchoice.equals("paper") && computerchoice.equals("paper")) || (userchoice.equals("rock") && computerchoice.equals("rock")) || (userchoice.equals("scissors") && computerchoice.equals("scissors"))) {
System.out.println("IT'S A TIE!");
ties++;
return 3;
} else if ((userchoice.equals("paper") && computerchoice.equals("rock")) || (userchoice.equals("rock") && computerchoice.equals("scissors")) || (userchoice.equals("scissors") && computerchoice.equals("paper"))) {
System.out.println("YOU WIN!");
wins++;
return 1;
} else {
System.out.println("YOU LOSE!");
losts++;
return 2;
}
}
public static String computerChoose() {
Random generator = new Random();
String[] answer = new String[3];
answer[0] = "paper";
answer[1] = "rock";
answer[2] = "scissors";
return answer[generator.nextInt(3)];
}
public static void main(String[] args) {
String play;
Scanner keyboard = new Scanner(System. in );
System.out.println("The Game of Paper, Rock, Scissors");
System.out.println("Do you need instructions (y or n)?");
String help = keyboard.nextLine();
if (help.equals("y")) instructions();
int result = playGame();
System.out.println("Play again (y or n)?");
play = keyboard.nextLine();
if (play.equals("y"));
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
do {} while (play == "y"); {
playGame();
int count = 0;
count++;
}
}
}
There are two issues here:
The code isn't inside the do-while loop, it's after it.
String equality should be checked with equals not with ==.
So:
int count = 0;
do { // Note the code inside the do-while block
playGame();
count++;
} while (play.equals("y")); // Note the use of equals
Do the following:
do {
play = keyboard.nextLine();
if (play.equals("y")){
}
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
} while (play.equals("y"));
In order to calculate the games scores make those variable global.
public class PRS {
static Scanner keyboard = new Scanner(System. in );
int ties = 0, wins = 0, losts = 0;

Categories

Resources