I am currently struggling to implement the while loop in my game as it always gives me an infinity loop. The idea is to continue the game except only when user types "-1"
// declare variables
int player, computer;
int counter = 0;
// player input
System.out.println("Rock, Paper, Scissors!");
System.out.print("Enter 0 for paper, 1 for Scissors, or 2 for Rock (-1 to quit) : ");
player = sc.nextInt();
while (player != -1) {
// switch statement for player
switch (player) {
case 0:
System.out.println("Player picks Paper");
break;
case 1:
System.out.println("Player picks Scissors");
break;
case 2:
System.out.println("Player picks Rock");
break;
case -1:
System.exit(-1);
break;
default:
System.out.println("Invalid input");
}
// generate a random number for computer
Random randomGen = new Random();
computer = randomGen.nextInt(3);
// switch statement for computer
switch (computer) {
case 0:
System.out.println("Computer picks Paper");
break;
case 1:
System.out.println("Computer picks Scissors");
break;
case 2:
System.out.println("Computer picks Rock");
break;
default:
}
// output for each condition
if (player == 2 && computer == 1)
System.out.println("Player Wins!");
else if (player == 1 && computer == 0)
System.out.println("Player Wins!");
else if (player == 0 && computer == 2)
System.out.println("Player Wins!");
else if (computer == 1 && player == 0)
System.out.println("Computer Wins!");
else if (player == 0 && computer == 2)
System.out.println("Computer Wins!");
else if (player == 1 && computer == 2)
System.out.println("Computer Wins!");
else
System.out.println("Draw");
sc.close();
}
You never update your player value. Add player = sc.nextInt() to the end of the loop body. Or, do something like
int player;
while ((player = sc.nextInt()) != -1) {
And, I believe you should also remove the call to sc.close();
Related
I'm attempting to create a game of "Rock Paper Scissors Lizard Spock", and want the user to be able to put in either the integers assigned to the variables (Rock=0, Paper=1, Scissors=2, Lizard=3 and Spock=4) and also be able to enter the words "Rock", "Paper", "Scissors", "Lizard" or "Spock". Could you help me include a part of the code where I can assign the string inputs to integers. I also do not want to change the main framework of the code. I also know that the website says not to paste the entire file, but I cannot think of another way to show my problem. Please note that I have been using a website called SoloLearn. Any help would be greatly appreciated.
import java.util.Scanner;
public class RockPaperScissorsLizardSpock {
final static int ROCK = 0;
final static int PAPER = 1;
final static int SCISSORS = 2;
final static int LIZARD = 3;
final static int SPOCK = 4;
public static void main(String[] args) {
double r = Math.random();
int computerChoice = (int)(3.0 * r);
Scanner input = new Scanner(System.in);
System.out.print("Enter 0 for Rock, 1 for Paper, 2 for Scissors, 3 for Lizard, 4 for Spock: ");
int playerChoice = input.nextInt();
System.out.println(computerChoice);
int playerChoice = 0;
switch (playerChoice) {
case "Rock":
playerChoice = 0;
break;
case "Paper":
playerChoice = 1;
break;
case "Scissors":
playerChoice = 2;
case "Lizard":
playerChoice = 3;
case "Spock":
playerChoice = 4;
if (computerChoice == playerChoice) {
System.out.println("Tie");
}
else if (computerChoice == ROCK && playerChoice == SCISSORS) {
System.out.println("I chose Rock,You chose Scissors, Rock crushes Scissors, You lose.");
}
else if (computerChoice == SCISSORS && playerChoice == PAPER) {
System.out.println("I chose Scissors, You chose Paper, Scissors cut Paper, You lose.");
}
else if (computerChoice == PAPER && playerChoice == ROCK) {
System.out.println("I chose Paper,You chose Rock, Paper covers Rock, You lose.");
}
else if (computerChoice == LIZARD && playerChoice == PAPER) {
System.out.println("I chose Lizard, You chose Paper, Lizard eats Paper, You lose.");
}
else if (computerChoice == SPOCK && playerChoice == SCISSORS) {
System.out.println("I chose Spock, You chose Scissors, Spock smashes Scissors, You lose.");
}
else if (computerChoice == ROCK && playerChoice == LIZARD) {
System.out.println("I chose Rock, You chose Lizard, Rock crushes Lizard, You lose.");
}
else if (computerChoice == SCISSORS && playerChoice == LIZARD) {
System.out.println("I chose Scissors, You chose Lizard, Scissors decapitates Lizard, You lose.");
}
else if (computerChoice == SPOCK && playerChoice == PAPER) {
System.out.println("I chose Spock, You chose Paper, Paper disproves Spock, You lose.");
}
else if (computerChoice == SPOCK && playerChoice == ROCK) {
System.out.println("I chose Spock, You chose Rock, Spock vaporizes Rock, You lose.");
}
else if (computerChoice == SCISSORS && playerChoice == ROCK) {
System.out.println("I chose Scissors, You chose Rock, Rock crushes Scissors, You win.");
}
else if (computerChoice == PAPER && playerChoice == SCISSORS) {
System.out.println("I chose Paper, You chose Scissors, Scissors cut Paper, You win.");
}
else if (computerChoice == ROCK && playerChoice == PAPER) {
System.out.println("I chose Rock, You chose Paper, Paper covers Rock,You win.");
}
else if (computerChoice == PAPER && playerChoice == LIZARD) {
System.out.println("I chose Paper, You chose Lizard, Lizard eats Paper, You win.");
}
else if (computerChoice == SCISSORS && playerChoice == SPOCK) {
System.out.println("I chose Scissors, You chose Spock, Spock smashes Scissors, You win.");
}
else if (computerChoice == LIZARD && playerChoice == ROCK) {
System.out.println("I chose Lizard, You chose Rock, Rock crushes Lizard, You win.");
}
else if (computerChoice == LIZARD && playerChoice == SCISSORS) {
System.out.println("I chose Lizard, You chose Scissors, Scissors decapitates Lizard, win.");
}
else if (computerChoice == PAPER && playerChoice == SPOCK) {
System.out.println("I chose Paper, You chose Spock, Paper disproves Spock, You win.");
}
else if (computerChoice == ROCK && playerChoice == SPOCK) {
System.out.println("I chose Rock, You chose Spock, Spock vaporizes Rock, You win.");
}else{
System.out.println("Error");
}
}
}
}
If you want that your user can input 2 Values for 1 condition you can convert the value from playerChoice to String for a temp String and then make a switch case for it like the following:
String tempString = Integer.toString(playerChoice);
switch (tempString) {
case "0":
case "Rock":
playerChoice = 0;
break;
case "1":
case "Paper":
playerChoice = 1;
break;
case "2":
case "Scissors":
playerChoice = 2;
break;
case "3":
case "Lizard":
playerChoice = 3;
break;
case "4":
case "Spock":
playerChoice = 4;
break;
}
You could put your allowed inputs in a map, key being the text and value being the associated number:
private static final Map<String, Integer> ALLOWED_INPUTS = Collections.unmodifiableMap(Map.of(
"ROCK", 0,
"PAPER", 1,
"SCISSORS", 2,
"LIZARD", 3,
"SPOCK", 4
));
Then, in your main function, check if the map contains a key that corresponds to the user input, if so get the corresponding value. If not, check if the user entered a number. Keep looping while the resulting number either way isn't in the map's values.
Scanner in = new Scanner(System.in);
int playerChoice = -1;
String input;
while(!ALLOWED_INPUTS.containsValue(playerChoice)) {
input = in.nextLine();
if (ALLOWED_INPUTS.containsKey(input))
playerChoice = ALLOWED_INPUTS.get(input);
else {
try {
playerChoice = Integer.parseInt(input);
} catch(NumberFormatException e) {}
}
}
System.out.println("You choosed choice number " + playerChoice);
Assuming : Either Words or Integers are entered as inputs.
Steps for this solution:
Always Entering String Input: String choice = input.next();
Checking if choice contains only digits, if yes,convert this to Integer else don't do anything.
if entered input is words, it will go to switch first,then set playerChoice and run properly.
if entered input is digit, it will assign converted integer to playerChoice first, then it will go to switch but as no default exists, it will run properly.
String choice = input.next();
if (choice.matches("\\d+"))
playerChoice = Integer.parseInt(choice);
switch (choice.toUpperCase()) {
case "ROCK":
playerChoice = 0;
break;
case "PAPER":
playerChoice = 1;
break;
case "SCISSORS":
playerChoice = 2;
break;
case "LIZARD":
playerChoice = 3;
break;
case "SPOCK":
playerChoice = 4;
break;
}
How can I compare a string with an int? I am making a Rock-paper-scissors game and how do I turn the string the user enters in to a int so the program can check who had won? Such as if the users enters "rock" the program registers that as 0 and so on?
package rpc;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* Random number generator */
Random random = new Random();
/* Scanner object for input */
Scanner scanner = new Scanner(System.in);
/*
* Integer variables to hold the user and computer choice.
* 0 = Rock
* 1 = Paper
* 2 = Scissors
*/
String userChoice;
int computerChoice;
// Showing prompt and user input
System.out.println("Enter move (0 = Rock; 1 = Paper; 2 = Scissors):");
userChoice = scanner.nextLine();
// Checking if userChoice is 0, 1, or 2.
if (!userChoice.equalsIgnoreCase("Scissors") && !userChoice.equalsIgnoreCase("Paper")
&& !userChoice.equalsIgnoreCase("rock")) {
System.out.println("Invalid choice. Ending program.");
// Exit program
Main.main(args);
}
// Generating random computer choice
computerChoice = random.nextInt(3);
// Determining the winner
// If the choices are equal, it's a tie.
if (userChoice == computerChoice) {
if (userChoice == 0) {
System.out.println("Both players chose rock!");
} else if (userChoice == 1) {
System.out.println("Both players chose paper!");
} else {
System.out.println("Both players chose scissors!");
}
// Exit program
System.exit(0);
}
if (userChoice == 0) { // User chooses rock
if (computerChoice == 1) {
System.out.println("You chose rock; Computer chose paper");
System.out.println("Computer wins!");
} else {
System.out.println("You chose rock; Computer chose scissors");
System.out.println("You win!");
}
} else if (userChoice == 1) { // User chooses paper
if (computerChoice == 0) {
System.out.println("You chose paper; Computer chose rock");
System.out.println("You win!");
} else {
System.out.println("You chose paper; Computer chose scissors");
System.out.println("Computer wins!");
}
} else { // User chooses scissors
if (computerChoice == 0) {
System.out.println("You chose scissors; Computer chose rock");
System.out.println("Computer wins!");
} else {
System.out.println("You chose scissors; Computer chose paper");
System.out.println("You win!");
}
}
scanner.close();
}
}
You could use an enum to enumerate the three possible choices:
enum Hand {
ROCK,
PAPER,
SCISSORS;
public static Hand from(String input) {
for (Hand hand : values()) {
if (hand.name().equalsIgnoreCase(input)) {
return hand;
}
}
throw new IllegalArgumentException("Invalid choice: " + input);
}
}
Enums have an intrinsic integer value (that corresponds to the position they were defined at). ROCK.ordinal() will return 0, for example.
Just use pareseInt and convert string to int
For ex :
if(Integer.parseInt(userChoice) == computerChoice)
Make sure that the inputs are not null and formattable to int
edit : change parese to parse
Retrieving a random item from ArrayList
This is not the exact answer to your question (Integer.parseInt(myInt)) but you could try something more readable like this, avoiding the use of unnecessary Integers. And simplifies your code
Generate your arrayList and then pick the random "computer" choice.
List<String> posibilities = Arrays.asList("rock","paper","scissors");
String computerChoice = possibilites.get(Math.random(3));
then do your comparaison ;)
/* Chose the possibilities */
List<String> posibilities = Arrays.asList("rock","paper","scissors");
/* Scanner object for input */
Scanner scanner = new Scanner(System.in);
// Showing prompt and user input
System.out.println("Enter move (0 = Rock; 1 = Paper; 2 = Scissors):");
String userChoice = scanner.nextLine();
userChoice = possibilities.get(Integer.parseInt(userChoice));
// Checking if userChoice is 0, 1, or 2.
if(!possibilities.contains(userChoice)) {
System.out.println("Invalid choice. Ending program.");
// Exit program
Main.main(args);
}
// Generating random computer choice
String computerChoice = possibilites.get(Math.random(3));
// Determining the winner
// If the choices are equal, it's a tie.
if(userChoice.equals(computerChoice)) {
System.out.println("Both players chose " + userChoice);
// Exit program
System.exit(0);
}
System.out.println("You chose " + userChoice + "; Computer chose " + computerChoice);
if(userChoice.equals("rock")) { // User chooses rock
if(computerChoice.equals("paper")) {
System.out.println("Computer wins!");
} else {
System.out.println("You win!");
}
}
else if(userChoice.equals("paper")) { // User chooses paper
if(computerChoice.equals("rock")) {
System.out.println("You win!");
} else {
System.out.println("Computer wins!");
}
} else { // User chooses scissors
if(computerChoice.equals("Scissors")) {
System.out.println("Computer wins!");
} else {
System.out.println("You win!");
}
}
scanner.close();
I am writing a program that prompts the user to play rock paper scissors against the computer. I'm having trouble calling the int rpsls method from the main method. I am not sure how to call it from the main method because I need the value of user input from the main method to be inputted into the rpsls method. The following is what I have so far, and yes it's full of errors, but I am mainly concerned with calling the method.
UPDATE - I added some more code, and now the program will compile. However, when I try to run it it just freezes. Can anyone help find a solution to make the program run?
import java.util.Scanner;
public class Rpsls
{
public static void main (String [] args) {
int wins = 0;
int ties = 0;
int losses = 0;
int retVal = 0;
int output = rpsls(retVal);
//while loop
Scanner input = new Scanner (System.in);
int x = input.nextInt();
while (x > 0 && x <= 5) {
//input gesture
System.out.println(" ROCK PAPER SCISSORS LIZARD SPOCK");
System.out.println(" (1) (2) (3) (4) (5)");
System.out.print("Enter your choice, or 0 to end: ");
//call rpsls for inputted gesture
int gesture = input.nextInt();
rpsls(gesture);
//returned values: loss, win, or tie
if (output == -1 ) {
losses++;
}
else if (output == 0) {
ties++;
}
else {
wins++;
}
//count wins and losses
//end while loop
//print sum of wins and losses.
}
System.out.println("You won " + wins + " games, lost " + losses + " games, and tied " + ties + " games.");
}
public static int rpsls(int gesture) {
//generate random gesture for computer
int attack = (int)(Math.random()*5);
//decide who won
int wins = 0; int losses = 0; int ties = 0;
int retVal = 0;
if (gesture == 1 && attack == 1) {
System.out.println("You chose ROCK.");
System.out.println("Computer chose ROCK.");
System.out.println("It's a tie!");
retVal = 0;
}
if (gesture == 1 && attack == 2) {
System.out.println("You chose ROCK.");
System.out.println("Computer chose PAPER.");
System.out.println("PAPER covers ROCK.");
System.out.println("Computer wins!");
retVal = -1;
}
if (gesture == 1 && attack == 3) {
System.out.println("You chose ROCK.");
System.out.println("Computer chose SCISSORS.");
System.out.println("ROCK crushes SCISSORS.");
System.out.println("You win!");
retVal = 1;
}
if (gesture == 1 && attack == 4) {
System.out.println("You chose ROCK.");
System.out.println("Computer chose LIZARD.");
System.out.println("ROCK crushes LIZARD.");
System.out.println("You win!");
retVal = 1;
}
if (gesture == 1 && attack == 5) {
System.out.println("You chose ROCK.");
System.out.println("Computer chose SPOCK.");
System.out.println("SPOCK vaporizes ROCK.");
System.out.println("Computer wins!");
retVal = -1;
}
if (gesture == 2 && attack == 1) {
System.out.println("You chose PAPER.");
System.out.println("Computer chose ROCK.");
System.out.println("PAPER covers ROCK.");
System.out.println("You win!");
retVal = 1;
}
if (gesture == 2 && attack == 2) {
System.out.println("You chose PAPER.");
System.out.println("Computer chose PAPER.");
System.out.println("It's a tie!");
retVal = 0;
}
if (gesture == 2 && attack == 3) {
System.out.println("You chose PAPER.");
System.out.println("Computer chose SCISSORS.");
System.out.println("SCISSORS cut PAPER.");
System.out.println("Computer wins!");
retVal = -1;
}
if (gesture == 2 && attack == 4) {
System.out.println("You chose PAPER.");
System.out.println("Computer chose LIZARD.");
System.out.println("LIZARD eats PAPER.");
System.out.println("Computer wins!");
retVal = -1;
}
if (gesture == 2 && attack == 5) {
System.out.println("You chose PAPER.");
System.out.println("Computer chose SPOCK.");
System.out.println("PAPER disproves SPOCK.");
System.out.println("You win!");
retVal = 1;
}
if (gesture == 3 && attack == 1) {
System.out.println("You chose SCISSORS.");
System.out.println("Computer chose ROCK.");
System.out.println("ROCK crushes SCISSORS.");
System.out.println("Computer wins!");
retVal = -1;
}
if (gesture == 3 && attack == 2) {
System.out.println("You chose SCISSORS.");
System.out.println("Computer chose PAPER.");
System.out.println("SCISSORS cut PAPER.");
System.out.println("You win!");
retVal = 1;
}
if (gesture == 3 && attack == 3) {
System.out.println("You chose SCISSORS.");
System.out.println("Computer chose SCISSORS.");
System.out.println("It's a tie!");
retVal = 0;
}
if (gesture == 3 && attack == 4) {
System.out.println("You chose SCISSORS.");
System.out.println("Computer chose LIZARD.");
System.out.println("SCISSORS decapitate LIZARD.");
System.out.println("You win!");
retVal = 1;
}
if (gesture == 3 && attack == 5) {
System.out.println("You chose SCISSORS.");
System.out.println("Computer chose SPOCK.");
System.out.println("SPOCK smashes SCISSORS.");
System.out.println("Computer wins!");
retVal = -1;
}
if (gesture == 4 && attack == 1) {
System.out.println("You chose LIZARD.");
System.out.println("Computer chose ROCK.");
System.out.println("ROCK crushes LIZARD.");
System.out.println("Computer wins!");
retVal = -1;
}
if (gesture == 4 && attack == 2) {
System.out.println("You chose LIZARD.");
System.out.println("Computer chose PAPER.");
System.out.println("LIZARD eats PAPER.");
System.out.println("You win!");
retVal = 1;
}
if (gesture == 4 && attack == 3) {
System.out.println("You chose LIZARD.");
System.out.println("Computer chose SCISSORS.");
System.out.println("SCISSORS decapitate LIZARD.");
System.out.println("Computer wins!");
retVal = -1;
}
if (gesture == 4 && attack == 4) {
System.out.println("You chose LIZARD.");
System.out.println("Computer chose LIZARD.");
System.out.println("It's a tie!");
retVal = 0;
}
if (gesture == 4 && attack == 5) {
System.out.println("You chose LIZARD.");
System.out.println("Computer chose SPOCK.");
System.out.println("LIZARD poisons SPOCK.");
System.out.println("You win!");
retVal = 1;
}
if (gesture == 5 && attack == 1) {
System.out.println("You chose SPOCK.");
System.out.println("Computer chose ROCK.");
System.out.println("SPOCK vaporizes ROCK.");
System.out.println("You win!");
retVal = 1;
}
if (gesture == 5 && attack == 2) {
System.out.println("You chose SPOCK.");
System.out.println("Computer chose PAPER.");
System.out.println("PAPER disproves SPOCK.");
System.out.println("Computer wins!");
retVal = -1;
}
if (gesture == 5 && attack == 3) {
System.out.println("You chose SPOCK.");
System.out.println("Computer chose SCISSORS.");
System.out.println("SPOCK smashes SCISSORS.");
System.out.println("You win!");
retVal = 1;
}
if (gesture == 5 && attack == 4) {
System.out.println("You chose SPOCK.");
System.out.println("Computer chose LIZARD.");
System.out.println("LIZARD poisons SPOCK.");
System.out.println("Computer wins!");
retVal = -1;
}
if (gesture == 5 && attack == 5) {
System.out.println("You chose SPOCK.");
System.out.println("Computer chose SPOCK.");
System.out.println("It's a tie!");
retVal = 0;
}
return retVal;
}
}
This line:
int rpsls = gesture(x);
...creates an int varaible called rpsls in your main function, calls a method called gesture, and passes x into it.
You may have meant:
int gesture = input.nextInt();
rpsls(gesture);
...which calls nextInt on your Scanner to get a number from the user, remembers it as gesture, then calls your existing rpsls method, passing in gesture.
You are calling gesture(int) and you were probably trying to invoke int rpsls(int gesture)
int retVal = rpsls(gesture);
Some variables are initialized and declared inside code blocks that affects its lifetime, for example input is inside the while block so it will not work outside that;
int rpsls(int gesture) is poorly designed: the computer should shoose a random value for rock/paper/scissors and then compare it with the user;
Your code doesn't work, you need to at least:
move int x = input.nextInt();after while (x > 0 && x <= 5)statement, without this it will not use you input for game,
move Scanner declaration before first use of it, couse it will not compile,
change all 'x' in rpsls method on 'gesture', the rpsls method don't have an access to 'x' variable form main method;
initialize 'retVal' variable (give it a value), for exaple 0, to avoid compilation error;
change int rpsls = gesture(x);for for example int rpsls = rpsls(x);by this, it will proceed on your input
After those changes, it works fine in my opinion.
EDIT:
You should remove int output = rpsls(retVal); and retVal declaration from main, couse it is useless i think, and add int output = rpsls(x); after x = input.nextInt(); then it works properly.
Also replace int x = input.nextInt(); with int gesture = input.nextInt();
i'm new to java. i'm writing a sample of rock paper scissors game. the user input 0,1,2 for rock, paper, scissors respectively. the program randomly generated the result. i almost managed to get it work but the only thing i'm stuck at is how to STOP THE FOR LOOP IF ONE OF THE SIDE WINS CONSECUTIVELY FOR THREE TIMES.
THIS IS THE ORIGINAL QUESTION
Write a program that plays scissor-rock-paper game. The rule is that a scissor wins against a paper, a
rock wins against a scissor, and a paper wins against a rock. The program represent scissor as 0, rock
as 1, and paper as 2.
The game is to be played between the computer and a player. The program will prompt the user to
enter the number of rounds to win. For example, if the user enter 4 then the winner has to win at
least 3 out of the 4 rounds. If either party win 3 times consecutively, the game ends early without the
fourth round. If the user enter 5 rounds, the winner has to win at least 3 out of the 5 rounds. The
same rule of consecutive 3-wins also apply. After the user has entered the number of rounds, the
computer randomly generates a number between 0 and 2. The program then prompts the user to
enter a number 0, 1, or 2. After the last round (subject to the above mentioned early-winner-rule),
the program display a message indicating whether the computer or the user wins, loses, or draws.
THIS IS MY CODE.
package assignment1;
import java.util.Scanner;
import java.util.Random;
public class question1_9 {
// This program is used to play scissor-rock-paper game.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random random = new Random();
int scissor = 0, rock = 1, paper = 2, round, userinput,comprand, userresult = 0, compresult = 0, control,j,k;
// Variables used in this program is declared and initialized.
/* Number of rounds wished to be play are obtained from user. */
System.out.println("WELCOME TO ROCK PAPER SCISSOR GAME. ");
System.out.println("PLEASE ENTER THE NUMBER OF ROUND YOU WANT TO PLAY: ");
round = scan.nextInt();
control = (round/2)+1;
for(int i = 0; i<round; i++)
{
if (compresult == control | userresult == control)
{
break;
}
System.out.println("ROUND " + (i+1));
System.out.println("PLEASE ENTER:\n 0 for scissor \n 1 for rock \n 2 for paper \n");
userinput = scan.nextInt();
comprand = random.nextInt(3);
if (userinput == 0)
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("DRAW!!!");
i--;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("YOU WIN!!!");
userresult++;
}
}
else if (userinput == 1)
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("YOU WIN!!!");
userresult++;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("DRAW!!!");
i--;
}
}
else
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("YOU WIN!!!");
userresult++;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("DRAW!!!");
i--;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
}
}
if(compresult == userresult)
System.out.println("\n\nFINAL RESULT IS DRAW!!!");
else if (compresult > userresult)
System.out.println("\n\nFINAL RESULT IS COMPUTER WIN!!!");
else
System.out.println("\n\nFINAL RESULT IS YOU WIN!!!");
}
}
use break; statement when you want to get out of current loop.
At top of loop,
store the wins in an array
String[] results=new String[rounds];
store your results as "user" or "comp" for each round and at the end of loop do this
if((results[i].equals("user") && results[i-1].equals("user") && results[i-2].equals("user") || (results[i].equals("comp") && results[i-1].equals("comp") && results[i-2].equals("comp")))
{
break;
}
Like shreyas said, use a break statement when you want to exit a loop.
I would set compresult to zero whenever the player wins a round, and set userresult to zero whenever the computer wins. Then, at the top of the loop, right after the { add:
if(userResult == 3 || computerResult == 3 || round/2 > 10)
{
break;
}
Some code comes from shreyas's original post.
Ok, so I have programmed a simple rock paper scissors game using user input to play. The user types their choice, a random function chooses the computers go and then a result is produced. After this the program is terminated because it has finished. I want to use a while loop so that when the game is finished, it starts again, and then the program will stop if the user types in exit or quit, which can easily be done by just saying something like while playerGo != exit, play the game blah blah. However, I cannot get this to work, can someone help me please, I'm a Java noob :)
import java.util.Scanner;
public class RockPaperScissors{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int compGoInt;
String compGo;
String playerGo;
System.out.println("You can type 'Exit' to quit the game at any time.");
System.out.print("Please enter your choice. Rock, Paper or Scissors: ");
playerGo = input.nextLine();
compGoInt = (int) (Math.random() * 3);
switch (compGoInt){
case 0:
compGo = "Rock";
break;
case 1:
compGo = "Paper";
break;
case 2:
compGo = "Scissors";
break;
default:
compGo = "Error";
System.out.println("Error.");
break;
}
if (playerGo.equals(compGo)){
System.out.println("Computer chooses "+compGo);
System.out.println("It's a draw!");
}
else if ((playerGo.equalsIgnoreCase("Rock") && compGo.equalsIgnoreCase("Scissors")) ||
(playerGo.equalsIgnoreCase("Paper") && compGo.equalsIgnoreCase("Rock")) ||
(playerGo.equalsIgnoreCase("Scissors") && compGo.equalsIgnoreCase("Paper"))){
System.out.println("Computer chooses "+compGo);
System.out.println("Player Wins!");
}
else if ((compGo.equalsIgnoreCase("Rock") && playerGo.equalsIgnoreCase("Scissors")) ||
(compGo.equalsIgnoreCase("Paper") && playerGo.equalsIgnoreCase("Rock")) ||
(compGo.equalsIgnoreCase("Scissors") && playerGo.equalsIgnoreCase("Paper"))){
System.out.println("Computer chooses "+compGo);
System.out.println("Computer Wins!");
}
else{
System.out.println("Something has gone wrong!");
System.out.println("Player chose "+playerGo);
System.out.println("Computer chose "+compGo);
}
}
}
Simply put:
while(true) {
if(playerGo.equalsIgnoreCase("Exit")) break;
else //GameLogic
}
Though, if I may say so, you should have the user choose a number, since any letter input is prone to errors.
For clarification purposes:
import java.util.Scanner;
public class RockPaperScissors{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int compGoInt;
String compGo;
String playerGo;
while(true) {
System.out.println("You can type 'Exit' to quit the game at any time.");
System.out.print("Please enter your choice. Rock, Paper or Scissors: ");
playerGo = input.nextLine();
if(playerGo.equalsIgnoreCase("Exit")) break; //Checks for exit condition.
else { //GameLogic
compGoInt = (int) (Math.random() * 3);
switch (compGoInt){
case 0:
compGo = "Rock";
break;
case 1:
compGo = "Paper";
break;
case 2:
compGo = "Scissors";
break;
default:
compGo = "Error";
System.out.println("Error.");
break;
}
if (playerGo.equals(compGo)){
System.out.println("Computer chooses "+compGo);
System.out.println("It's a draw!");
}
else if ((playerGo.equalsIgnoreCase("Rock") && compGo.equalsIgnoreCase("Scissors")) ||
(playerGo.equalsIgnoreCase("Paper") && compGo.equalsIgnoreCase("Rock")) ||
(playerGo.equalsIgnoreCase("Scissors") && compGo.equalsIgnoreCase("Paper"))){
System.out.println("Computer chooses "+compGo);
System.out.println("Player Wins!");
}
else if ((compGo.equalsIgnoreCase("Rock") && playerGo.equalsIgnoreCase("Scissors")) ||
(compGo.equalsIgnoreCase("Paper") && playerGo.equalsIgnoreCase("Rock")) ||
(compGo.equalsIgnoreCase("Scissors") && playerGo.equalsIgnoreCase("Paper"))){
System.out.println("Computer chooses "+compGo);
System.out.println("Computer Wins!");
}
else{
System.out.println("Something has gone wrong!");
System.out.println("Player chose "+playerGo);
System.out.println("Computer chose "+compGo);
}
}
}
}
}
You can add a boolean variable IsGameRunning = true.
wrap the whole login in a while loop that checks the state of IsGameRunning.
Add a case to the switch statement that checks for user input "-1", and when the user enters "-1" as input the case changes IsGameRunning variable to false.
Simple and should work
boolean running = true;
do{
System.out.println("You can type 'Exit' to quit the game at any time.");
System.out.print("Please enter your choice. Rock, Paper or Scissors: ");
playerGo = input.nextLine();
running = !(playerGo.equalsIgnoreCase('Exit') || playerGo.equalsIgnoreCase('Quit'));
if(running){
//logic
compGoInt = (int) (Math.random() * 3);
...
}
}while(running)
do while -> input needs to be asked at least once.
and for
if (playerGo.equals(compGo)){
System.out.println("Computer chooses "+compGo);
System.out.println("It's a draw!");
}
playerGo.equals(compGo) -> playerGo.equalsIgnoreCase(compGo) like the rest of your code