I made a Rock Paper Scissors game for my CS class (senior in highschool) and the shell file my teacher gave me noted that I have to put the do while loop in the runner, but I don't see why? My code works, but she said it'd be better to write it in the runner? Why? Also, how can I write it more efficiently? (Note: I'm a total beginner, and prior to taking this class, had no knowledge of coding. Haven't learned recursion yet.)
my code:
import java.util.Random;
import java.util.Scanner;
public class RockPapersScissors {
private String user;
private int computer;
public RockPapersScissors(){
setPlayers(" ");
}
public RockPapersScissors(String s){
setPlayers(s);
}
public void setPlayers(String s){
user=s;
}
public void play(){
Scanner keyboard = new Scanner(System.in);
Random num = new Random();
int numUser = 0;
String playAgain = "";
do{
System.out.print("Rock-Paper-Scissors - pick your weapon[R,P,S] :: ");
user = keyboard.next();
System.out.println("player has "+ user);
switch(user){
case "R": numUser = 0; break;
case "P": numUser = 1; break;
case "S": numUser = 2; break;
case "r": numUser = 0; break;
case "p": numUser = 1; break;
case "s": numUser = 2; break;
default: System.out.println("Please enter a valid choice. Restart game.\n"); continue;
}
computer = num.nextInt(3);
switch(computer){
case 0: System.out.println("computer has R"); break;
case 1: System.out.println("computer has P"); break;
case 2: System.out.println("computer has S"); break;
}
if(numUser == computer){
System.out.println("!Draw Game!");
}else if(numUser == 0){
if(computer == 1){
System.out.println("!Computer Wins <<Paper Covers Rock>>!");
}if(computer == 2){
System.out.println("!Player Wins <<Rock Breaks Scissors>>!");
}
}else if(numUser == 1){
if(computer == 2){
System.out.println("!Computer Wins <<Scissors cuts paper>>!");
}if(computer == 0){
System.out.println("!Player Wins <<Paper Covers Rock>>!");
}
}else if(numUser == 2){
if(computer == 0){
System.out.println("!Computer Wins <<Rock Breaks Scissors>>!");
}if(computer == 1){
System.out.println("!Player Wins <<Scissors cuts paper>>!");
}
}
System.out.print("\nDo you want to play again? ");
playAgain = keyboard.next();
System.out.println("\n");
}while(playAgain.equals("y") || playAgain.equals("yes") || playAgain.equals("Y"));
System.out.println("Goodbye.");
keyboard.close();
}
}
my runner:
public class RPSRunner {
public static void main(String[] args) {
RockPapersScissors test = new RockPapersScissors();
test.play();
}
}
It all depends on the notion of what a "game" is. If a game is assumed to be a single round of RPS, with no keeping of score, then the teacher's prescribed solution would be good.
However, as soon as you need to retain some form of session state between rounds, such as a score, then you would have to make a design decision: Does the runner contain the logic to keep score, or does the game? Typically, one would have the game keep score, and the runner should know as little as possible about the internal logic of the game.
In another case, you may be asked to expand the runner so that you can choose between two different games. The second game might be "Black Jack", in which case you not only need to keep score, but also keep track of which cards have been played. As you can see the, the complexity of the runner can grow needlessly with your teacher's approach.
The teacher should have given you better requirements, or you should have asked.
By the way, this happens all the time in the real world.
I would say that each round of Rock/Paper/Scissors is independent of all the others. I would have written a single method that took in player 1 and 2 values and returned a winner. Get that to work and then put it in the game loop to play over and over again.
There could be a second overloaded version of play() method with an embedded computer player that would randomly choose and call the two-player version.
Perhaps that is what your teacher meant, too. Why not ask them instead of making us read his/her mind? You can learn a lot using the Socratic method.
Don't worry about efficiency; it doesn't matter for such a trivial application. Make it run; make it run correctly; make it run fast.
Related
I am creating a game of rock paper scissors, on the playGame() method I cannot get the code to work, it only prints out what the user and computer has chosen. I have tried to figure out where i am going wrong and all i could get it to do was the print out a draw but it made the game always draw!
I haven't finished the method yet, i also need to add a score counter up to 3.
import java.util.Random;
public class RockPaperScissors
{
private InputReader reader;
private int yourScore;
private int computerScore;
private Random ran;
/**
* Constructor for objects of class RockPaperScissors
*/
public RockPaperScissors()
{
reader = new InputReader();
yourScore = 0;
computerScore = 0;
ran = new Random(1);
}
/**
* An example of a method - replace this comment with your own
*/
public void printPrompt()
{
System.out.println();
System.out.println();
System.out.println("Enter your choice, paper, rock or scissors >");
}
public String userChoice()
{
String input = reader.getInput();
input = input.trim().toLowerCase();
return input;
}
public String computerChoice()
{
Random ran = new Random();
int myRanInt = ran.nextInt(3);
String computerRanChoice ="";
switch(myRanInt) {
case 0: computerRanChoice = "paper";
break;
case 1: computerRanChoice = "scissors";
break;
case 2: computerRanChoice = "rock";
break;
}
return computerRanChoice;
}
public void playGame()
{
printPrompt();
String userMove = this.userChoice();
System.out.println("you have chosen " + userMove + " and the computer has chosen " + computerChoice());
int roundWinner = 0;
int count = 1;
switch(roundWinner) {
case 0: computerChoice().equals(userChoice());
System.out.println("This game is a draw");
break;
case 1: computerChoice().equals("rock");
System.out.println(userMove.equals("paper") ? "The computer is the winner" : "You are the winner");
break;
case 2: computerChoice().equals("paper");
System.out.println(userMove.equals("scissors") ? "The computer is the winner" : "You are the winner");
break;
case 3: computerChoice().equals("scissors");
System.out.println(userMove.equals("rock") ? "The computer is the winner" : "You are the winner");
break;
}
}
}
In the switch block of playgame() method, you have initialised the value of roundWinner as 0, so it will always print out case 0, i.e. the draw statement.
Using switch in this case seems a bit tricky, as you are working with two variables, the computer's and the player's choice, while switch works on only one variable. Try using some if statements first and then work your logic to switch if needed
Prompt: "Write a program to play the pig game against the computer. At each turn, the current player will
roll a pair of dice and accumulates points. The goal is to reach to 100 or more points before your
opponent does. (For the testing purposes use 30 instead of 100 points) If, on any turn, the player
rolls a 1, all the points accumulated for that round are forfeited and the control of the dice
moves to the other player. If the player rolls two 1s in one turn, the player loses all the points
accumulated thus far are forfeited and the control moves to the other player. The player may
voluntarily turn over the control of the dice after each roll. Therefore player must decide to roll
again (be a pig) and risk losing points, or relinquish control of the dice, possibly allowing the
other player to win. Computer is going to flip a coin to choose the first player "
My problem: I got the program to output that either the computer or the player is going first based on a coin flip. However, how would I actually prompt the program to run a method of the person chosen to start first, and then how would I switch between the computer and player at the end of each turn? Btw, I know this code is incomplete, but I hope that my question makes sense.
Code so far:
import java.util.*;
public class NavaiPigGame
{
public static final int POINT = 30;
public static final int FORFEIT_POINTS = 20;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
play(rand,input);
}
// desription of game
public static void description()
{
System.out.println("***********************************************************************************");
System.out.println("Write a program to play the pig game against the computer. At each turn, the current player will");
System.out.println("roll a pair of dice and accumulates points. The goal is to reach to 100 or more points before your");
System.out.println("opponent does. (For the testing purposes use 30 instead of 100 points) If, on any turn, the player");
System.out.println("rolls a 1, all the points accumulated for that round are forfeited and the control of the dice");
System.out.println("moves to the other player. If the player rolls two 1s in one turn, the player loses all the points");
System.out.println("accumulated thus far are forfeited and the control moves to the other player. The player may");
System.out.println("voluntarily turn over the control of the dice after each roll. Therefore player must decide to roll");
System.out.println("again (be a pig) and risk losing points, or relinquish control of the dice, possibly allowing the");
System.out.println("other player to win. Computer is going to flip a coin to choose the first player");
System.out.println("***********************************************************************************");
System.out.println("lets start the fun");
}
//flips a coin and decides who starts the game
public static String flipCoin(Random rand)
{
int coin = rand.nextInt(2);
String comp = "";
switch (coin)
{
case 0: comp = "heads";
break;
case 1: comp = "tails";
break;
}
return comp;
}
public static int rollDice(Random rand)
{
int dice1 = rand.nextInt(6)+1;
int dice2 = rand.nextInt(6)+1;
System.out.println("Dice 1: " +dice1);
System.out.println("Dice 2: " +dice2);
return dice1+dice2;
}
// select a random name of the computer via arrays
public static String nameComputer(Random rand)
{
int name = rand.nextInt(10);
String compName = "";
switch (name)
{
case 0: compName = "Lisa";
break;
case 1: compName = "Kathy";
break;
case 2: compName = "Hali";
break;
case 3: compName = "Jack";
break;
case 4: compName = "Alex";
break;
case 5: compName = "Max";
break;
case 6: compName = "Jill";
break;
case 7: compName = "James";
break;
case 8: compName = "Martha";
break;
case 9: compName = "Lauren";
break;
}
return compName;
}
public static void play(Random rand, Scanner input)
{
int playerScores = 0;
int playerTotal = 0;
int computerScores = 0;
int computerTotal = 0;
boolean gameOver = false
boolean turnOver = false
description();
String compName = nameComputer(rand);
System.out.println("Hi my name is " + compName);
System.out.print("What is your name? ");
String name = input.nextLine();
System.out.println("Hi " + name + ", I am flipping the coin to determine who goes first");
System.out.print("press any key to start the game. ");
input.nextLine();
String flip = flipCoin(rand);
int turn;
if (flip.equals("heads"))
{
turn = 1;
System.out.println("You are going to start the game");
}
else
{
turn = 0;
System.out.println(compName + " is going to start the game");
}
}
}
Create :
A playTurn(int turn) function (1 for the player, 0 for the computer) that handle a play turn (roll dice, calculate point etc.)
A boolean function that check wether there is a winner or not. Example : isWinner(int player) (again, 1 for the player, 0 for the computer)
Use the function a first time in your if() else statment like that :
if (flip.equals("heads"))
{
turn = 1;
System.out.println("You are going to start the game");
playTurn(turn);
}
else
{
turn = 0;
System.out.println(compName + " is going to start the game");
playTurn(turn);
}
Then you can add :
do {
if(turn == 1){
turn = 0;
playTurn(turn);
}else{
turn == 1;
playTurn(turn);
}
while ( !isWinner(1)|| !isWinner(0) );
This is not very well designed, but it should hopefully give you a hint on what to do next.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I wanted to lead this question by letting everyone know that this is my first time on stack overflow so if I do not conform to question-asking standards please let me know.
I'm making a program that plays Rock, Paper, Scissors with you, and right as I was approaching the back end of the project this error came up:
Exception in thread "main" java.lang.NullPointerException
at RockPaperScissors.getPlayerThrow(RockPaperScissors.java:93)
at RockPaperScissors.main(RockPaperScissors.java:26)
I'm not sure where I would be using null, but thats what you're here for.
Here is the entire project compiled as it currently is:
public class RockPaperScissors {
//sets the constants
static final int ROCK = 1;
static final int PAPER = 2;
static final int SCISSORS = 3;
//creates some variables
static int playerThrow, computerThrow, result, timesPlayed, playerWins, computerWins;
static String playAgain;
static Scanner fru;
/*
* The Results
* 0 = tie
* 1 = Player win
* 2 = Computer win
*/
public static void main(String[] args) {
//this do while loop is the whole game
do {
//decides the throws of the players
playerThrow = getPlayerThrow();
computerThrow = (int)(Math.random() * 3 + 1);
switch(playerThrow) {
//compares and displays the computer and player
//choices if the player chooses rock
case ROCK:
switch(computerThrow) {
case ROCK:
result = 0;
System.out.println("You threw rock and the computer threw rock!");
break;
case PAPER:
result = 2;
System.out.println("You threw rock and the computer threw paper!");
break;
case SCISSORS:
result = 1;
System.out.println("You threw rock and the computer threw scissors!");
break;
} break;
//compares and displays the computer and player
//choices if the player throws paper
case PAPER:
switch(computerThrow) {
case ROCK:
result = 1;
System.out.println("You threw paper and the computer threw rock!");
break;
case PAPER:
result = 2;
System.out.println("You threw paper and the computer threw paper!");
break;
case SCISSORS:
result = 3;
System.out.println("You threw paper and the computer threw scissors!");
break;
} break;
//compares and displays the computer and player
//choices if the player throws scissors
case SCISSORS:
switch(computerThrow) {
case ROCK:
result = 2;
System.out.println("You threw scissors and the computer threw rock!");
break;
case PAPER:
result = 1;
System.out.println("You threw scissors and the computer threw paper!");
break;
case SCISSORS:
result = 0;
System.out.print("You threw scissors and the computer threw scissors!");
break;
} break;
}
timesPlayed ++;
// will compare and decide the winner of the two players
finish();
} while (timesPlayed < 3);
}
public static int getPlayerThrow() {
//prompts weapon choice and stores said choice
System.out.println("Choose your weapon of choice:\n(1 for rock, 2 for paper, 3 for scissors)");
int choice = fru.nextInt();
//checks for validity and returns the choice
if (choice != 1 && choice != 2 && choice != 3) {
System.out.print("Not a valid input!\n Please try again: ");
choice = fru.nextInt();
}
return choice;
}
//compares and decides the winner of the two players
public static void finish() {
//displays the winner of the round accourding to aforementioned possible results
switch(result) {
case 0:
System.out.println("Its a tie!"); break;
case 1:
System.out.println("You are victorious! Man over machine!");
playerWins++; break;
case 2:
System.out.println("The computer has taken the round! Technological singularity approaches!");
computerWins++; break;
}
//cheks if the match is over and displays messages accordingly
switch(timesPlayed) {
case 1: break;
case 2:
if (playerWins == 2 || computerWins == 2) {
if (playerWins == 2) {
System.out.println("You win the match! Congratulations!\nWould you like to play another match?\n(y for yes, n for no)");
timesPlayed = 5;
playAgain = fru.nextLine();
//checks for validity
if (playAgain != "y" || playAgain != "n") {
System.out.print("Not a valid input!\n Please try again: ");
playAgain = fru.nextLine();
}
}
else if (computerWins == 2) {
System.out.println("The computer wins the match!\nPlay again! I know you can beat it.\n(y for yes, n for no)");
timesPlayed = 5;
playAgain = fru.nextLine();
//checks for validity
if (playAgain != "y" || playAgain != "n") {
System.out.print("Not a valid input!\n Please try again: ");
playAgain = fru.nextLine();
}
}
} break;
//will happen for any amount of times played over 2
default:
if (playerWins == 2) {
System.out.println("You win the match! Congratulations!\nWould you like to play another match?\n(y for yes, n for no)");
playAgain = fru.nextLine();
//checks for validity
if (playAgain != "y" || playAgain != "n") {
System.out.print("Not a valid input!\n Please try again: ");
playAgain = fru.nextLine();
}
}
else if (computerWins == 2) {
System.out.println("The computer wins the match!\nPlay again! I know you can beat it.\n(y for yes, n for no)");
playAgain = fru.nextLine();
//checks for validity
if (playAgain != "y" || playAgain != "n") {
System.out.print("Not a valid input!\n Please try again: ");
playAgain = fru.nextLine();
}
}
}
}
}
I understand neither what the error means nor where it comes from. The only information that I have about it comes from skimming google for the error, but it is tough when the questions asked or examples posted are not specific to my project. I have taken multiple steps towards fixing it but none of them seem to do anything.
This could be a complex coding problem or a single character that I have missed, but any and all help is appreciated! Thank you!
I see plenty of places where you use the fru scanner but absolutely none where you actually initialise it. What you have basically boils down to:
import java.util.Scanner;
public class Test {
static Scanner fru;
public static void main(String[] arg) {
int x = fru.nextInt();
System.out.println(x+1);
}
}
and, when you run that, you'll see the exception. You'll need to do something like:
fru = new Scanner(System.in);
before you attempt to do any scanning. Until you do that, trying to dereference it will cause the exception you're getting. In other words, something like:
import java.util.Scanner;
public class Test {
static Scanner fru;
public static void main(String[] arg) {
fru = new Scanner(System.in);
int x = fru.nextInt();
System.out.println(x+1);
}
}
which runs successfully.
In terms of finding these problems in future, you would do well to look at the error message you're actually getting:
Exception in thread "main" java.lang.NullPointerException
at RockPaperScissors.getPlayerThrow(RockPaperScissors.java:93)
at RockPaperScissors.main(RockPaperScissors.java:26)
Despite the fact your error message doesn't quite match your code (line numbers are off by three), examining the stack trace to track down where and what the errors are is a vital skill.
In this case, it's the line:
int choice = fru.nextInt();
and you would therefore assume it's because fru has not been set correctly. From there, it a matter of tracking back to where you actually set fru to something useful. In this particular case, that doesn't exist so it's relatively easy to figure out.
So here's the code for this. I have a switch statement so that the user can enter their choice between the given options printed out. When I enter 2, 3, or any other number it works fine. But once I select the first option (playing the game) it'll go to that method and work fine. But once the method ends and the case breaks the compiler returns to the top of the while loop and won't let the user choose another option. Instead it'll choose the first option once more and continue on this infinite loop. How can I fix this?
package rockPaperScissors;
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
System.out.println("Welcome to Rock Paper Scissors!");
Scores scores = new Scores(); //Object that holds two integers and allows you to increment them
Scanner playerChoice = new Scanner(System.in);
int option = 0;
do{
System.out.println("Select an option!");
System.out.println("1: Play the game");
System.out.println("2: Check the score");
System.out.println("3: Quit the game");
option = playerChoice.nextInt(); /*Shouldn't this line stop and let me
enter another option for the menu? */
switch(option) {
case 1: playGame(scores);
break;
case 2: getScore(scores);
break;
case 3: System.out.println("Thanks for playing!");
break;
default: System.out.println("You must pick one of given options\n");
break;
}
} while(option != 3);
playerChoice.close();
}
What I find odd is that this piece of code here works exactly as I want it to, but they're essentially the same:
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
System.out.println("Welcome to a simple menu that does nothing!\n");
Scanner input = new Scanner(System.in);
int menuChoice;
do{
System.out.println("Please select an option!\n");
System.out.println("1: This does nothing");
System.out.println("2: This also does nothing");
System.out.println("3: You guessed it, it does nothing");
System.out.println("4: Quit\n");
menuChoice = input.nextInt();
switch(menuChoice){
case 1: System.out.println("You chose option 1");
break;
case 2: System.out.println("You chose option 2");
break;
case 3: System.out.println("You chose option 3");
break;
case 4: System.out.println("Goodbye!");
break;
default: System.out.println("ENTER A VALID INPUT");
}
}while(menuChoice != 4);
input.close();
}
}
EDIT:
So playGame is a method that actually handles the rock paper scissors part of the game.
private static Scores playGame(Scores scores) {
System.out.println("Pick either rock, paper, or scissors");
//The player makes a choice
Scanner scanner = new Scanner(System.in);
String playerDecision = "";
if(scanner.hasNextLine()){
playerDecision = scanner.nextLine();
}
//Check to see if the player chose one of the given options
if(playerDecision.equalsIgnoreCase("rock") == false && playerDecision.equalsIgnoreCase("paper") == false && playerDecision.equalsIgnoreCase("scissors") == false){
System.out.println("You must select either rock, paper, or scissors");
scanner.close();
return scores;
}
//The computer makes a random choice
Random random = new Random();
String gameArray[] = {"rock", "paper", "scissors"};
int randNum = random.nextInt(3);
String computerChoice = gameArray[randNum];
System.out.println("You chose: " + playerDecision + "\nThe computer choice: " + computerChoice);
if(playerDecision.equalsIgnoreCase(computerChoice)){ //If it's a tie
System.out.println("It's a tie!");
scanner.close();
return scores;
} else if(playerDecision.equalsIgnoreCase("rock")){ //If the player chooses rock
if(computerChoice.equalsIgnoreCase("paper")){ //If the computer chooses paper
System.out.println("The computer wins!");
scores.incrementComputerScore();
scanner.close();
return scores;
} else if(computerChoice.equalsIgnoreCase("scissors")){ //If the computer chooses scissors
System.out.println("You win!");
scores.incrementPlayerScore();
scanner.close();
return scores;
}
} else if(playerDecision.equalsIgnoreCase("paper")){ //If the player chooses paper
if(computerChoice.equalsIgnoreCase("rock")){ //If the computer chooses rock
System.out.println("You win!");
scores.incrementPlayerScore();
scanner.close();
return scores;
}else if(computerChoice.equalsIgnoreCase("scissors")){ //If the computer chooses scissor
System.out.println("The computer wins!");
scores.incrementComputerScore();
scanner.close();
return scores;
}
} else if(playerDecision.equalsIgnoreCase("scissors")){ //If the player chooses scissors
if(computerChoice.equalsIgnoreCase("rock")){ //If the computer chooses rock
System.out.println("The computer wins!");
scores.incrementComputerScore();
scanner.close();
return scores;
}else if(computerChoice.equalsIgnoreCase("paper")){ //If the computer chooses paper
System.out.println("You win!");
scores.incrementPlayerScore();
scanner.close();
return scores;
}
}
scanner.close();
return scores;
}
You are closing your scanner at your playgame() method, by closing a scanner, you also closes its input stream that is used to construct it. This is explained in the javadoc for Scanner.close()
Because the input stream to the program is now closed, your main loop won't return any meaning full information for your scanner.nextInt() ( hasNextInt() will now return false) and because of the current implementation of scanner, it will return the last valid value.
To solve the problem, you can use multiple solutions.
Passing the scanner to playgame (recommended)
By adding a argument to playgame that accepts the orginal scanner, you prevent the fact that it needs to be closed inside the body of playgame
public void playGame(Score scores, Scanner scan) { // change arguments of constructor
....
// scanner.close() // Drop this line too
}
Not closing the scanner inside the playgame
There is another way to get around the problem, and that is by not closing the scanner inside the playgame method, this isn't recommend however, because a scanner may readahead on a stream and consume bytes targetted to the main menu, this problem isn't really large with your usecase of user interaction.
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.