Philana Philana - 1 month ago 7
Java Question

How to restart Rock Paper and Scissors game mutliple times until user quits in Java

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

}

Answer

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.

Comments