I'm having to make a paper rock scissors program that has the user enter in a choice, then tests it against the computer's choice. After every game, it should ask the player if they want to continue, and they should enter in 'Y' or 'N' to continue or quit. The best I could think was a while loop, and everything works fine except the very last bit.
import java.util.Scanner;
public class rockpaperscissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char cont = 'y';
while (cont == 'y'){
int com = (int)(Math.random() * 3);
System.out.println("Paper (0), Rock (1), or Scizzors (2)?");
int hum = input.nextInt();
if (com==(hum))
System.out.println("It's a tie!");
else if (hum == 0)
{
if (com == 1)
System.out.println ("You chose paper, computer chose rock You Win!");
else if (com == 2)
System.out.println ("You chose paper, Computer chose scissors You Lose!");
}
else if (hum == 1)
{
if (com == 2)
System.out.println ("You chose Rock, computer chose scissors You Win!");
else if (com == 0)
System.out.println ("You chose Rock, Computer chose paper You Lose!");
}
else if (hum == 2)
{
if (com == 0)
System.out.println ("You chose Scissors, computer chose paper You Win!");
else if (com == 1)
System.out.println ("You chose Scissors, Computer chose rock You Lose!");
}
System.out.println("Would you like to continue? (Y/N)");
cont = input.nextLine().charAt(0);
}
}
}
When I run it, the loop runs fine, the game is played, but then I get a 'string out of index range' error. Any idea how to resolve this?
Your nextInt() just reads the number from the input buffer, leaving the new line in it. So when you call input.nextLine() you're getting an empty line - the rest of the first line after the number. You should read the next-line and make sure it's not empty. If it is, just read it again.
Incidentally, your code that figures out who won is a bit cumbersome. If I were you, I would try to make it a little more general and clean. Think about a solution that can handle a more complex game, such as Rock Paper Scissors Lizard Spock without adding too much code.
When you get the answer from the user, you don't read the next line so the scanner still has a new line character. Then when you read the nextline you read that new line, and therefore there is no charat(0).
Change:
cont = input.nextLine().charAt(0);
to:
cont = input.next().charAt(0);
package rockpaper;
import java.util.Scanner;
/**
*
* #author Allen E.
*/
public class RockPaper {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int rock = 0;
int paper = 1;
int Scissors = 2;
int user = 0;
int computer = 0;
int gamesplayed = 0;
Scanner scan = new Scanner(System.in);
while (gamesplayed < 3)
{
System.out.println("Rock = 0 , Paper = 1, Scissors = 2");
String userinput = scan.nextLine();
int convertinput = Integer.valueOf(userinput);
int Computerinput = (int)(Math.random()*3);
if (Computerinput == 1 && convertinput == 0)
{
System.out.println("Paper beats Rock " +
"\nThe computer won");
gamesplayed++;
computer++;
}
else if (convertinput == 1 && Computerinput == 0)
{
System.out.println("Paper beats Rock " +
"\nYou Win!");
gamesplayed++;
user++;
}
if (Computerinput == 0 && convertinput == 2)
{
System.out.println("Rock beats Scissors " +
"\nThe computer won");
gamesplayed++;
computer++;
}
else if (convertinput == 0 && Computerinput == 2)
{
System.out.println("Rock beats Scissors " +
"\nYou Win!");
gamesplayed++;
user++;
}
if (Computerinput == 2 && convertinput == 1)
{
System.out.println("Scissors beats Paper " +
"\nThe computer won");
gamesplayed++;
computer++;
}
else if (convertinput == 2 && Computerinput == 1 )
{
System.out.println("Scissors beats Paper " +
"\nYou Win");
gamesplayed++;
user++;
}
/*************************************************
* *
* *
* Handling a tie *
* *
* *
*************************************************/
if (Computerinput == 0 && convertinput == 0)
{
System.out.println("Rock ties Rock " +
"\nTie");
}
if (Computerinput == 1 && convertinput == 1)
{
System.out.println("Paper ties Paper " +
"\nTie");
}
if (Computerinput == 2 && convertinput == 2)
{
System.out.println("Scissors ties Scissors " +
"\nTie");
}/*End of While Loop*/
}
}
}
Related
I am working on a "Rock, Paper, Scissors" game for my intro java class. Here is the prompt: Create a game of "Rock, Paper, Scissors" where the computer randomly chooses rock, paper, or scissors. Let the user enter a number of 1, 2, or 3, each representing one of three choices. Determine a winner. Game should ask the user to play again and continue if yes and stop if no. Once the user stops playing the program should print the total number of wins.
I am having issues with declaring my variables in the correct places since I am trying to use a method so I can call it to play the game again.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Would you like to play \"Rock, Paper, Scissors?\"");
System.out.println("Answer \"yes\" or \"no\"");
input.next();
String answer = input.next();
}
public static int letsPlay()
{
int cMove;
int userMove = 0;
int cScore = 0;
int pScore = 0;
int tie = 0;
int rounds = 0;
Random r = new Random();
while (answer.equalsIgnoreCase("yes"))
cMove = r.nextInt(3)+1;
System.out.println("Choose your move!");
System.out.println("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ");
userMove = input.nextInt();
while(input.hasNextInt()) {
if (userMove!=1 && userMove!=2 && userMove!=3)
{
System.out.println("Invalid move. Try again.");
System.out.println("Enter your move: ");
input.nextInt();
}
}
if(userMove==1)
{
System.out.println("You have chosen Rock!");
}
else if(userMove==2)
{
System.out.println("You have chosen Paper!");
}
else if(userMove==3)
{
System.out.println("You have chosen Scissors!");
}
if (userMove == cMove)
{
System.out.println("Tie Game!");
System.out.println("");
tie++;
rounds++;
} else if (cMove==1 && userMove==3)
{
System.out.println("Computer chose Rock!");
System.out.println("Rock beats Scissors!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
else if (cMove==1 && userMove==2)
{
System.out.println("Computer chose Rock!");
System.out.println("Paper beats Rock!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==2 && userMove==3)
{
System.out.println("Computer chose Paper!");
System.out.println("Scissors beats Paper!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==2 && userMove==1)
{
System.out.println("Computer chose Paper!");
System.out.println("Paper beats Rock!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
else if (cMove==3 && userMove==1)
{
System.out.println("Computer chose Scissors!");
System.out.println("Rock beats Scissors!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==3 && userMove==2)
{
System.out.println("Computer chose Scissors!");
System.out.println("Scissors beats Paper!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
System.out.println("Would you like to play again?");
System.out.println("Answer \"yes\" or \"no\"");
input.next();
String yesorno = input.next();
if(yesorno.equalsIgnoreCase("yes"))
{
letsPlay();
}
else {
System.out.println ("Here are the final scores after " + rounds +" rounds:");
System.out.println ("You: "+ pScore + "Computer: "+ cScore + "Ties: " + tie);
}
}
}
Edited code so far, it says missing return statement from my letsPlay method:
Not sure how to proceed..
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Would you like to play \"Rock, Paper, Scissors?\"");
System.out.println("Answer \"yes\" or \"no\"");
String answer = input.next();
letsPlay(answer);
}
public static int letsPlay(String answer)
{
int cMove;
int userMove = 0;
int cScore = 0;
int pScore = 0;
int tie = 0;
int rounds = 0;
Random r = new Random();
Scanner input = new Scanner(System.in);
cMove = r.nextInt(3)+1;
while (answer.equalsIgnoreCase("yes"))
System.out.println("Choose your move!");
System.out.println("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ");
userMove = input.nextInt();
while(input.hasNextInt()) {
if (userMove!=1 && userMove!=2 && userMove!=3)
{
System.out.println("Invalid move. Try again.");
System.out.println("Enter your move: ");
input.nextInt();
}
}
if(userMove==1)
{
System.out.println("You have chosen Rock!");
}
else if(userMove==2)
{
System.out.println("You have chosen Paper!");
}
else if(userMove==3)
{
System.out.println("You have chosen Scissors!");
}
if (userMove == cMove)
{
System.out.println("Tie Game!");
System.out.println("");
tie++;
rounds++;
} else if (cMove==1 && userMove==3)
{
System.out.println("Computer chose Rock!");
System.out.println("Rock beats Scissors!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
else if (cMove==1 && userMove==2)
{
System.out.println("Computer chose Rock!");
System.out.println("Paper beats Rock!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==2 && userMove==3)
{
System.out.println("Computer chose Paper!");
System.out.println("Scissors beats Paper!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==2 && userMove==1)
{
System.out.println("Computer chose Paper!");
System.out.println("Paper beats Rock!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
else if (cMove==3 && userMove==1)
{
System.out.println("Computer chose Scissors!");
System.out.println("Rock beats Scissors!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==3 && userMove==2)
{
System.out.println("Computer chose Scissors!");
System.out.println("Scissors beats Paper!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
System.out.println("Would you like to play again?");
System.out.println("Answer \"yes\" or \"no\"");
input.next();
answer = input.next();
if(answer.equalsIgnoreCase("yes"))
{
main(null);
}
else {
System.out.println ("Here are the final scores after " + rounds +"
rounds:");
System.out.println ("You: "+ pScore + "Computer: "+ cScore + "Ties: "
+ tie);
}
}
}
You aren't passing the String answer to your letsPlay() method and that's because your letsPlay() method can't take a String as a parameter because it is defined without parameters being passed. A solution to this problem is to change the method definition to require a String variable.
public static int letsPlay()
turns into
public static int letsPlay(String userInput)
then inside your method you use the variable userInput instead of String answer in the letsPLay(String userInput) method.
The next issue you run into is you're calling the method again within the method. This is called recursion and it's perfectly legal, however it is not ideal in this circumstance. You should exit the game once it's over and ask the user in your main() method if they'd like to play again.
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
do
{
System.out.println("Would you like to play \"Rock, Paper, Scissors?\"");
System.out.println("Answer \"yes\" or \"no\"");
String answer = input.nextLine();
letsPlay(answer);
}while(answer.equalsIgnoreCase("yes"));
}
Firstly, in your main method one input.next() is extra and of no use so remove it.
Now write a statement in main method as follows after String answer = input.next();
:
letsPlay(answer);
Put a parameter in letsPlay() method as follows:
public static void letsPlay(String answer) {
//Your code..........
//Some last edits...
Scanner input = new Scanner(System.in);
answer = input.next();
if(!(answer.equalsIgnoreCase("yes")))
{
System.out.println ("Here are the final scores after "+rounds+"
rounds:");
System.out.println("You:"+pScore+"Computer: "+cScore+"Ties: "+tie);
}
}
No required extra method for calling any line.
You can call main
Move codes to main from letsPlay method.
remove: letsPlay()
use: main(null)
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Would you like to play \"Rock, Paper, Scissors?\"");
System.out.println("Answer \"yes\" or \"no\"");
input.next();
String answer = input.next();
// moved codes to following place from letsPlay
int cMove = 0;
...
if(yesorno.equalsIgnoreCase("yes"))
{
main(null); // changed with letsPlay()
}
...
}
}
cMove not initilazed exception occurred. So use this:
int cMove = 0;
Now, any errors not occurred.
Move the Scanner object inside the constructor. Currently you have it outside and your code does not know what it is.
Here is the modified portion of your code:
public static int letsPlay()
{
int cMove;
int userMove = 0;
int cScore = 0;
int pScore = 0;
int tie = 0;
int rounds = 0;
Random r = new Random();
Scanner input = new Scanner(System.in); // move the input object inside the constructor
Hope it helps.
There are many errors in your code. You can check out the comments in the code for a proper understanding of the code.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
// initialising variable to 0 for score calculation
int cScore = 0;
int pScore = 0;
int tie = 0;
int rounds = 0;
Scanner input = new Scanner(System.in);
System.out.println("Would you like to play \"Rock, Paper, Scissors?\"");
System.out.println("Answer \"Yes\" or \"No\"");
String answer = input.next();
if (answer.equalsIgnoreCase("yes")) {
// Calling method letsPlay with arguments answer, cScore, pScore, tie, rounds
// initially cScore = pScore = tie = rounds = 0
letsPlay(answer, cScore, pScore, tie, rounds);
}
}
// letsPlay Method
public static void letsPlay(String answer, int cScore, int pScore, int tie, int rounds) {
int cMove;
int userMove;
Random r = new Random();
Scanner input = new Scanner(System.in);
// loop untill user chose no
while (true) {
// to get random move of computer on every iteration
cMove = r.nextInt(3) + 1;
System.out.println("--------------------------------------------------");
System.out.println("Choose your move!");
System.out.println("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ");
userMove = input.nextInt();
// loop until user input number 1 or 2 or 3
while (userMove != 1 && userMove != 2 && userMove != 3) {
System.out.println("Invalid move. Try again.");
System.out.println("--------------------------------------------------");
System.out.println("Choose your move: ");
System.out.println("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ");
userMove = input.nextInt();
}
// Print statement for user move
if (userMove == 1) {
System.out.println("You have chosen Rock!");
} else if (userMove == 2) {
System.out.println("You have chosen Paper!");
} else {
System.out.println("You have chosen Scissors!");
}
// Print statement for computer move
if (cMove == 1) {
System.out.println("Computer chose Rock!");
} else if (cMove == 2) {
System.out.println("Computer chose Paper!");
} else {
System.out.println("Computer chose Scissors!");
}
// Winning, Loosing and Tie conditions
// increment round to 1 every time
// increment the winner, looser or tie on every iteration
if (userMove == cMove) {
System.out.println("Tie Game!");
tie++;
rounds++;
} else if (cMove == 1 && userMove == 3) {
System.out.println("Rock beats Scissors!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
} else if (cMove == 1 && userMove == 2) {
System.out.println("Paper beats Rock!");
System.out.println("Player Wins!");
pScore++;
rounds++;
} else if (cMove == 2 && userMove == 3) {
System.out.println("Scissors beats Paper!");
System.out.println("Player Wins!");
pScore++;
rounds++;
} else if (cMove == 2 && userMove == 1) {
System.out.println("Paper beats Rock!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
} else if (cMove == 3 && userMove == 1) {
System.out.println("Rock beats Scissors!");
System.out.println("Player Wins!");
pScore++;
rounds++;
} else if (cMove == 3 && userMove == 2) {
System.out.println("Scissors beats Paper!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
// Asking again to play or not
System.out.println("\nWould you like to play again?");
System.out.println("Answer \"Yes\" or \"No\"");
answer = input.next();
if (answer.equalsIgnoreCase("yes")) {
// If yes the call letsPlay(answer, cScore, pScore, tie, rounds);
// But this time value of cScore, pScore, tie, rounds is changed
// according to conditions
letsPlay(answer, cScore, pScore, tie, rounds);
} else {
// Print if user says didn't want to play again
System.out.println("==========================================");
System.out.println("\nHere are the final scores after " + rounds + " rounds:");
System.out.println("You : " + pScore + "\nComputer : " + cScore + "\nTies : " + tie);
}
// Exit if user didn't want to play again
break;
}
}
}
I'm new to programming and have been attempting to code a simple Rock Paper Scissors game in Java, but I'm stuck with two problems. The game worked correctly prior to me adding a for loop in order to make the game last for 5 rounds each time, but now with the loop it just repeats the same result line 4 times after entering 1 input, rather than allowing me to enter more inputs and generate several results. I also tried putting in an invalid input message, where if the user inputs anything other than 1, 2 or 3 the program outputs "Invalid user input.", but this doesn't work when ran and has just resulted in compiler error messages.
Any help would be greatly appreciated, thanks!
Here is the entirety of my code:
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static final int ROCK = 1;
public static final int PAPER = 2;
public static final int SCISSORS =3;
public static void main(String[] args) {
System.out.println("Let's play Rock, Paper, Scissors! (best out of 5)");
System.out.println("Enter either 1 for Rock, 2 for Paper or 3 for Scissors.");
Scanner input = new Scanner(System.in);
int numberGuessed = input.nextInt();
Random generator = new Random();
int computerNumber = generator.nextInt(3) + 1;
for (int round = 0; round < 4; round++) {
if (numberGuessed == computerNumber) {
System.out.print("It's a tie!");
}
if (numberGuessed == 1 && computerNumber == 2) {
System.out.println("You lose! I chose paper and paper smothers rock!");
}
else if (numberGuessed == 1 && computerNumber == 3) {
System.out.println("You win! I chose scissors and rock smashes scissors!");
}
else if (numberGuessed == 2 && computerNumber == 1) {
System.out.println("You win! I chose rock and paper smothers rock!");
}
else if (numberGuessed == 2 && computerNumber == 3) {
System.out.println("You lose! I chose scissors and scissors cut paper!");
}
else if (numberGuessed == 3 && computerNumber == 2) {
System.out.println("You win! I chose paper and scissors cut paper!");
}
else if (numberGuessed == 3 && computerNumber == 1) {
System.out.println("You lose! I chose rock and rock smashes scissors!");
}
else if (numberGuessed != 1 || numberGuessed != 2 || numberGuessed != 3) {
System.out.println("Invalid user input.");
}
}
You have not ended all of the curly braces properly which is leading to compiler error.
for (int round = 0; round < 4; round++) will end for upto 4 rounds, for 5 rounds of loop the condition can be like this: for (int round = 0; round < 5; round++)
The for loop should start before the input is taken each time so that it can process each input separately.
Try this:
import java.util.Random;
import java.util.Scanner;
class RockPaperScissors {
public static final int ROCK = 1;
public static final int PAPER = 2;
public static final int SCISSORS = 3;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Let's play Rock, Paper, Scissors! (best out of 5)");
for (int round = 0; round < 5; round++) {
System.out.println("Enter either 1 for Rock, 2 for Paper or 3 for Scissors.");
int numberGuessed = input.nextInt();
Random generator = new Random();
int computerNumber = generator.nextInt(3) + 1;
if (numberGuessed == computerNumber) {
System.out.println("It's a tie!");
} else if (numberGuessed == 1 && computerNumber == 2) {
System.out.println("You lose! I chose paper and paper smothers rock!");
} else if (numberGuessed == 1 && computerNumber == 3) {
System.out.println("You win! I chose scissors and rock smashes scissors!");
} else if (numberGuessed == 2 && computerNumber == 1) {
System.out.println("You win! I chose rock and paper smothers rock!");
} else if (numberGuessed == 2 && computerNumber == 3) {
System.out.println("You lose! I chose scissors and scissors cut paper!");
} else if (numberGuessed == 3 && computerNumber == 2) {
System.out.println("You win! I chose paper and scissors cut paper!");
} else if (numberGuessed == 3 && computerNumber == 1) {
System.out.println("You lose! I chose rock and rock smashes scissors!");
} else if (numberGuessed != 1 || numberGuessed != 2 || numberGuessed != 3) {
System.out.println("Invalid user input.");
}
System.out.println();
}
}
}
You set numbers and do 5 rounds on the same data. Move initialization of numberGuessed and computerNumber inside for loop.
Observe where your input and random number generator is. Think if that will repeat 5 times when your loop runs. Done?
If you haven't observed yet, let me elaborate: your input and random number generator is outside you for loop. That's IT.
Hello I'm stuck on how to keep the game going until the user decides to quit. I want to try any way possible to get the game to end and display the amount of losses, ties, and wins. I'm trying to use a while loop.
import java.util.Scanner;
import java.util.Random;
public class JavaApplication15 {
public static void main(String[] args) {
int ties = 0, wins = 0, losses = 0;
String comp = "";
String user = "";
Random choice = new Random();
String startover = "y";
while (startover.equals("y")) {
int computerchoice = choice.nextInt(3) + 1;
if (computerchoice == 1)
comp = "R";
else if (computerchoice == 2)
comp = "P";
else if (computerchoice == 3)
comp = "S";
Scanner scanner = new Scanner(System.in);
System.out.println("Enter rock (1), paper (2), or scissors (3) [no to quit]: ");
int player = scanner.nextInt();
if (player == 1) {
user = "R";
} else if (player == 2) {
user = "P";
} else if (player == 3) {
user = "S";
}
System.out.println("You choose: " + user);
System.out.println("Computer chooses: " + comp);
if (comp.equals(user)) {
System.out.println("It's a tie!");
ties++;
} else if (user.equals("R")) {
if (comp.equals("P"))
System.out.println("Computer wins! Paper beats rock!");
losses++;
} else if (comp.equals("S")) {
System.out.println("You win! Your rock beats the scissors!");
wins++;
} else if (user.equals("S")) {
if (comp.equals("P"))
System.out.println("You win! Scissor beats paper!");
wins++;
} else if (comp.equals("R")) {
System.out.println("Computer wins! Rock beats paper!");
losses++;
} else if (user.equals("P"))
if (comp.equals("R")) {
System.out.println("You win! Paper beats rock!");
wins++;
} else if (comp.equals("S")) {
System.out.println("Computer wins! Scissors beats paper!");
losses++;
}
}
{
System.out.println("Invalid input! Try again");
System.out.println("Your ties: " + ties);
System.out.println("Your wins: " + wins);
System.out.println("You losses: " + losses);
startover = "no";
}
}
instead of doing scanner.nextInt(); you could do
System.out.println("Enter rock (1), paper (2), or scissors (3) [\'n\' to quit]: ");
char selection = scanner.nextLine().charAt(0)
if(selection == '1'){ user = "R"; }
else if(selection == '2'){ user = "P"; }
else if(selection == '3'){ user = "S"; }
else if(selection == 'n'){
System.out.println(ties)
System.out.println(wins);
System.out.println(losses);
return;
}
this makes the selection variable a char, and you can test if it's 1, 2, or 3 (that is, the characters 1 2 or 3), and also check for 'n'.
since you're working in the main method, simply putting "return" will exit the program at that point.
You just need add a new option 4
else if (computerchoice == 4)
comp = "E";
} else if (comp.equals("E")) {
System.out.println("Your ties: " + ties);
System.out.println("Your wins: " + wins);
System.out.println("You losses: " + losses);
startover = "no";
}
I tried out your code as-is, and what I found out is that your code infact never stops. The while loop has no proper condition to exit. So I made some minor changes to make it work.
int ties = 0, wins = 0, losses = 0;
String comp = "";
String user = "";
Random choice = new Random();
String startover = "y";
Scanner scanner = new Scanner(System.in); //Scanner object should not be open in loop, it is a resource wastage
while (startover.equals("y")) {
int computerchoice = choice.nextInt(3) + 1;
if (computerchoice == 1)
comp = "R";
else if (computerchoice == 2)
comp = "P";
else if (computerchoice == 3)
comp = "S";
System.out.println("Enter rock (1), paper (2), or scissors (3) [no to quit]: ");
String input = scanner.nextLine(); //take input in string
int player ;
try {
player = Integer.parseInt(input); //see if actually number was given as input
} catch(Exception ex) {
break; //if not, then we assume player wants to quit
}
if (player == 1) {
user = "R";
} else if (player == 2) {
user = "P";
} else if (player == 3) {
user = "S";
}
System.out.println("You choose: " + user);
System.out.println("Computer chooses: " + comp);
if (comp.equals(user)) {
System.out.println("It's a tie!");
ties++;
} else if (user.equals("R")) {
if (comp.equals("P"))
System.out.println("Computer wins! Paper beats rock!");
losses++;
} else if (comp.equals("S")) {
System.out.println("You win! Your rock beats the scissors!");
wins++;
} else if (user.equals("S")) {
if (comp.equals("P"))
System.out.println("You win! Scissor beats paper!");
wins++;
} else if (comp.equals("R")) {
System.out.println("Computer wins! Rock beats paper!");
losses++;
} else if (user.equals("P"))
if (comp.equals("R")) {
System.out.println("You win! Paper beats rock!");
wins++;
} else if (comp.equals("S")) {
System.out.println("Computer wins! Scissors beats paper!");
losses++;
}
}
scanner.close(); //scanner was not closed before
System.out.println("Your ties: " + ties);
System.out.println("Your wins: " + wins);
System.out.println("You losses: " + losses);
startover = "no"; //redundant actually
I'm currently working on an assignment for my Intro to Java Course. I've completed majority of the assignment: refactor a Rock, Paper, Scissor game I created in the past but using methods. When my code is executed; it prints a welcome message, prompts for user input and then prints the user's choice and the CPU's choice.
My question: How do i implement a while loop into my methods so that after the code is executed it will run a best 2/3 games?
To my understanding, I know that I must use a loop in each method. Where the input from the user will be different and the cpu will generate another random move.
*Note: I'm not asking for a direct solution but for something conceptual as to what would be a good approach to this problem.
Below is my code:
package rpsmethods;
import java.util.Scanner;
import java.util.Random;
public class RPSMethods {
public static void displayOpeningMessage() {
System.out.println("Welcome to RPS Game 2.0!");
}
public static int getUserMove() {
Scanner input = new Scanner(System.in);
System.out.print("Select scissors (0), rock (1), or scissors (2): ");
int choice = 0;
if (input.hasNextInt()) {
choice = input.nextInt();
switch (choice) {
case 0:
System.out.println("You chose scissor!");
break;
case 1:
System.out.println("You chose rock!");
break;
case 2:
System.out.println("You chose paper!");
break;
default:
System.out.println("Not a valid input!");
System.out.print("Select scissors (0), rock (1), or scissors (2): ");
choice = input.nextInt();
}
}
return choice;
}
public static int getCPUMove() {
Random rnd = new Random();
int CPUMove = rnd.nextInt(3);
switch (CPUMove) {
case 0:
System.out.println("CPU chose scissor!");
break;
case 1:
System.out.println("CPU chose rock!");
break;
case 2:
System.out.println("CPU chose paper!");
break;
}
return CPUMove;
}
public static void determineWinner(int user, int cpu) {
//User win scenarios
if (user == 0 && cpu == 2) {
System.out.println("You win, Scissors beat Paper!");
} else if (user == 1 && cpu == 0) {
System.out.println("You win, Rock beats Scissors!");
} else if (user == 2 && cpu == 1) {
System.out.println("You win, Paper beats Rock!");
}
//Cpu win scenarios
if (user == 0 && cpu == 1) {
System.out.println("You lose, Rock beats Scissors!");
} else if (user == 1 && cpu == 2) {
System.out.println("You lose, Paper beats Rock!");
} else if (user == 2 && cpu == 0) {
System.out.println("You lose, Scissor beats Paper!");
}
//Draw scenarios
if (user == 0 && cpu == 0) {
System.out.println("You and CPU chose Scissor, it's a draw!");
} else if (user == 1 && cpu == 1) {
System.out.println("You and CPU chose Rock, it's a draw!");
} else if (user == 2 && cpu == 2) {
System.out.println("You and CPU chose Paper, it's a draw!");
}
}
public static void main(String[] args) {
displayOpeningMessage();
int userWinner = getUserMove();
int CpuWinner = getCPUMove();
determineWinner(userWinner, CpuWinner);
}
}
You can define two static variables to check the final winner in your
class:
static int cpuScore = 0;
static int humanScore = 0;
Then, you can set a value for that variables inside determineWinner like this:
if (CPU wins)
cpuScore++
else
humanScore++;
Then you can put your top level steps inside a loop like this:
while (cpuScore < 2 && humanScore < 2) {
...
}
So I am making a snakes and ladders game. If player1 and player2 land on the same grid they must have a duel. In my game the two players must have a game of rock paper scissors. I am having trouble getting my method to return the value int win to my subprogram Begin(). The win value will tell the begin method if either Player 1 or 2 won the rock paper scissors battle.
My code:
public static String Begin // Recieves data from the main method
{
// start Begin method
int win=0;
if(P1Position==P2Position||P2Position==P1Position){
System.out.println("==========================================================================");
System.out.println (player1+" is currently on square " + P1Position);
System.out.println (player2+" is currently on square " + P2Position);
System.out.println("==========================================================================");
firstplay(choice1,choice2);
determineOutcome(choice1,choice2,win);
if(win==1){
determineOutcome(choice1,choice2,win);
P2Position=P1Position-P1Roll;
}
else{
determineOutcome(choice1,choice2,win);
P1Position=P2Position-P2Roll;
}
}
}
public static void firstplay(int choice1,int choice2)throws IOException{//USER
// Initializes the BufferReader for user input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("DUEL!!!\nThe Player who wins this round of rock paper scissors will keep their spot,and the loser ther that player's old spot");
System.out.println("1=Rock\n2=Paper\n3=Scissors\n===========");
System.out.println(player1+" choose:");
choice1=Integer.parseInt(br.readLine());
System.out.println(player2+" choose:");
choice2=Integer.parseInt(br.readLine());
if(choice1==1){
System.out.println(player1+" chose Rock");//If user picked ROck
}
else if(choice1==2){
System.out.println(player1+" chose Paper");//If user picked Paper
}
else if(choice1==3){
System.out.println(player1+" chose Scissors");//If user picked Scissors
}
if(choice2==1){
System.out.println(player2+" chose Rock");
}
else if(choice2==2){
System.out.println(player2+" chose Paper");
}
else if(choice2==3){
System.out.println(player2+" chose Scissors");
}
}
public static int determineOutcome(int choice1,int choice2,int win)throws IOException{
// Initializes the BufferReader for user input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int die=0;
//Rock vs Papaer
if(choice2==1&&choice1==2){
System.out.println(player1+" WON PAPER BEATS ROCK");
System.out.println(player1+" keeps their spot");
win=1;
}
else if(choice2==2&&choice1==1){
System.out.println(player2+" WON PAPAER BEATS ROCK ");
System.out.println(player1+" keeps their spot");
win=0;
}
//Scissors vs Paper
else if(choice2==2&&choice1==3){
System.out.println(player1+" WON SCISSORS BEAT PAPER ");
System.out.println(player1+" keeps their spot");
win=1;
}
else if(choice2==3&&choice1==2){
System.out.println(player2+" WON SCISSORS BEAT PAPER ");
System.out.println(player2+" keeps their spot");
win=0;
}
//Rock vs Scissors
else if(choice2==3&&choice1==1){
System.out.println(player1+" WON ROCK BEATS SCISSORS ");
System.out.println(player1+" keeps their spot");
win=1;
}
else if(choice2==1&&choice1==3){
System.out.println(player2+" WON ROCK BEATS SCISSORS ");
System.out.println(player2+" keeps their spot");
win=0;
}
//Ties
else if(choice2==1&&choice1==1){
System.out.println("YOU'VE TIED. Play once again");
}
else if(choice2==2&&choice1==2){
System.out.println("YOU'VE TIED. Play once again");
}
else if(choice2==3&&choice1==3){
System.out.println("YOU'VE TIED. Play once again");
}
return win;
}
}//end class
Output:
yo Rolled a 2
po Rolled a 2
------------------------------------------------------------------------
==========================================================================
yo is currently on square 2
po is currently on square 2
==========================================================================
DUEL!!!
The Player who wins this round of rock paper scissors will keep their spot,and the loser ther that player's old spot
1=Rock
2=Paper
3=Scissors
===========
yo choose:
1
po choose:
3
yo chose Rock
po chose Scissors
==========================================================================
yo is currently on square 0
po is currently on square 2
==========================================================================
yo press r to roll
Expected:
Output:
yo Rolled a 2
po Rolled a 2
------------------------------------------------------------------------
==========================================================================
yo is currently on square 2
po is currently on square 2
==========================================================================
DUEL!!!
The Player who wins this round of rock paper scissors will keep their spot,and the loser ther that player's old spot
1=Rock
2=Paper
3=Scissors
===========
yo choose:
1
po choose:
3
yo chose Rock
po chose Scissors
yo won rock beats scissors.
yo keeps their spot
==========================================================================
yo is currently on square 2
po is currently on square 0
==========================================================================
yo press r to roll
You have to store the int value returned by the method determineOutcome.
win = determineOutcome(choice1,choice2,win);
if(win==1){
...
}
Note that is not necessary to pass win as a parameter to determineOutcome(), since you are not using its actual value. You could try this instead:
public static int determineOutcome(int choice1, int choice2) throws IOException
{
// Initializes the BufferReader for user input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int die = 0;
int win = 2; // 2 == TIE
//Rock vs Papaer
if (choice2 == 1 && choice1 == 2) {
System.out.println(player1 + " WON PAPER BEATS ROCK");
System.out.println(player1 + " keeps their spot");
win = 1;
} else if (choice2 == 2 && choice1 == 1) {
System.out.println(player2 + " WON PAPAER BEATS ROCK ");
System.out.println(player1 + " keeps their spot");
win = 0;
}
//Scissors vs Paper
else if (choice2 == 2 && choice1 == 3) {
System.out.println(player1 + " WON SCISSORS BEAT PAPER ");
System.out.println(player1 + " keeps their spot");
win = 1;
} else if (choice2 == 3 && choice1 == 2) {
System.out.println(player2 + " WON SCISSORS BEAT PAPER ");
System.out.println(player2 + " keeps their spot");
win = 0;
}
//Rock vs Scissors
else if (choice2 == 3 && choice1 == 1) {
System.out.println(player1 + " WON ROCK BEATS SCISSORS ");
System.out.println(player1 + " keeps their spot");
win = 1;
} else if (choice2 == 1 && choice1 == 3) {
System.out.println(player2 + " WON ROCK BEATS SCISSORS ");
System.out.println(player2 + " keeps their spot");
win = 0;
}
//Ties
else if (choice2 == 1 && choice1 == 1) {
System.out.println("YOU'VE TIED. Play once again");
} else if (choice2 == 2 && choice1 == 2) {
System.out.println("YOU'VE TIED. Play once again");
} else if (choice2 == 3 && choice1 == 3) {
System.out.println("YOU'VE TIED. Play once again");
}
return win;
}
Here you are declaring a local variable win, set it (0, 1 or 2) in the respective conditionals and return it at the end.
Note: If your conditionals to determine if a player won covers all the cases, you can replace the "Ties cases" with an else:
//Rock vs Scissors
else if (choice2 == 3 && choice1 == 1) {
System.out.println(player1 + " WON ROCK BEATS SCISSORS ");
System.out.println(player1 + " keeps their spot");
win = 1;
} else if (choice2 == 1 && choice1 == 3) {
System.out.println(player2 + " WON ROCK BEATS SCISSORS ");
System.out.println(player2 + " keeps their spot");
win = 0;
}
//Ties
else {
System.out.println("YOU'VE TIED. Play once again");
}