How to compare a String with an integer? - java

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();

Related

Returning two values to main method without arrays

Create a program named rockPaperScissors.java
The program should validate user input.
Game should ask the user to play again and continue if yes and stop if no.
Once the user stops playing, program should print the total number of wins for the computer and
for the user.
I am trying to learn programming from a book, so I am not good at this. I need to return the values of Cwin and Uwin to the main method, but I know how to return one value to it. I also have a problem with looping the question. I cannot use arrays and could only use the basic while loops (without the (true) and break).
import java.util.*;
public class rockPaperScissors
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Play again? Type yes or no.");
String YoN= input.next();
if (YoN.equalsIgnoreCase("yes"))
{
game();
}
else
{
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
}
}
public static void game()
{
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
Scanner console = new Scanner(System.in);
Random r = new Random();
int choice = console.nextInt();
int Uwin = 0;//user win count
int Cwin = 0;//computer win count
int result = -1;
if (choice > 1 || choice < 3)
{
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
int comp = r.nextInt(3) + 1;
if (comp == 1)
{
System.out.println("Computer chose rock.");
}
if (comp == 2)
{
System.out.println("Computer chose paper.");
}
if (comp == 3)
{
System.out.println("Computer chose scissors.");
}
if (choice == 1 && result == 2)
{
Cwin++;
}
if (choice == 2 && result == 3)
{
Cwin++;
}
if (choice == 3 && result == 1)
{
Cwin++;
}
if (choice == 2 && result == 1)
{
Uwin++;
}
if (choice == 3 && result == 2)
{
Uwin++;
}
if (choice == 1 && result == 3)
{
Uwin++;
}
}
}
If you want to return multiple values from a method you may use an array that stores the values in its elements. Check here.
However for this program there is no need for returning 2 values(and you also said "I cannot use arrays"). Instead you can have 2 global variables that record the number of times the player wins and the number of times the computer wins respectively. Lets call them playerWinCount and computerWinCount.
Now that we got that down, lets look at how we allow the user to replay the game. You say that can use only "basic while loops". Fine. What we do is we declare a variable choice that holds the user's entry when prompted to replay. We initialise choice to true and then keep asking the user if he'd like to play again until he decides not to.
String choice = "yes" ;
while(choice.equalsIgnoreCase("yes"))
{
playGame() ;
System.out.print("Play again(Yes/No)? ") ;
choice = scanner.next() ;
}
The playGame() method has the code to play the game.
The way we validate the user's entry is by using a length check. If the entry is out of range(i.e. from 1 to 3 inclusive) he'll be prompted to enter again.
boolean valid = false ;
while(valid == false) // loop will run until a valid number is entered
{
System.out.print("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors: ") ;
playerPick = scanner.nextInt() ;
// validation of the user's entry
if(playerPick < 1 || playerPick > 3)
System.out.println("Invalid entry! Try again.") ;
else
valid = true ;
}
Having acquired a valid user input, the next thing we do is get a random number as the computer's pick(you've done that). Then we check who won the game and increment the number of times the winner has won. We can do this using a number of if statements like this:
// first we check if the computer and player did not pick the same thing
if(playerPick != computerPick)
{
if(playerPick == 1 && computerPick == 3) // check if the player picked rock(1) and the computer picked scissors(3)
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else if(playerPick == 3 && computerPick == 2) // check if the player picked scissors(3) and the computer picked paper(2)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else if(playerPick == 2 && computerPick == 1) // check if the player picked paper(2) and the computer picked rock(1)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else // otherwise, the computer has won this round
{
computerWinCount++ ;
System.out.println("Computer won!") ;
}
}
else
{
System.out.println("It's a tie!");
}
Or we can just combine the 3 conditions of winning with the OR operator(||) and use just 2 if statements:
if(playerPick != computerPick)
{
if((playerPick == 1 && computerPick == 3) || (playerPick == 3 && computerPick == 2) || (playerPick == 2 && computerPick == 1))
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else
{
computerWinCount++ ;
System.out.println("Computer won!");
}
}
else
{
System.out.println("It's a tie!");
}
And that's about it.
Here's the entire code:
import java.util.* ;
public class RockPaperScissors
{
static Scanner scanner = new Scanner(System.in) ;
static int playerWinCount, computerWinCount ;
public static void main(String[] args)
{
playerWinCount = 0 ;
computerWinCount = 0 ;
String choice = "yes" ;
while(choice.equalsIgnoreCase("yes"))
{
playGame() ;
System.out.print("Play again(Yes/No)? ") ;
choice = scanner.next() ;
}
System.out.println("\nNumber of times you won: " + playerWinCount) ;
System.out.println("Number of times computer won: " + computerWinCount) ;
System.out.println("Goodbye!") ;
}
public static void playGame()
{
System.out.println("") ;
Random random = new Random() ;
int playerPick = -1 ;
int computerPick = -1 ;
boolean valid = false ;
while(valid == false) // loop will run until a valid number is entered
{
System.out.print("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors: ") ;
playerPick = scanner.nextInt() ;
// validation of the user's entry
if(playerPick < 1 || playerPick > 3)
System.out.println("Invalid entry! Try again.") ;
else
valid = true ;
}
computerPick = random.nextInt(3) + 1 ;
System.out.println("The computer picked " + computerPick) ;
// first we check if the computer and player did not pick the same thing
if(playerPick != computerPick)
{
if(playerPick == 1 && computerPick == 3) // check if the player picked rock(1) and the computer picked scissors(3)
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else if(playerPick == 3 && computerPick == 2) // check if the player picked scissors(3) and the computer picked paper(2)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else if(playerPick == 2 && computerPick == 1) // check if the player picked paper(2) and the computer picked rock(1)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else // otherwise, the computer has won this round
{
computerWinCount++ ;
System.out.println("Computer won!") ;
}
}
else
{
System.out.println("It's a tie!");
}
}
}
Let's go point by point.
You aren't taking the user input for determining the choice of playing in a while loop, so your game won't run more than once. You can take that input as:
while (true) {
System.out.println("Play again? Type yes or no.");
String YoN= input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
game():
} else {
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
break;
}
}
If user gives input other than yes, you're trying to print Cwin and Uwin, but you haven't declared those variables in the scope of main method. So your program won't compile anyways.
You can keep global variables in the class running main method.
public static int Cwin = 0;
public static int Uwin = 0;
Update
I've gone through your code and found a few more problems. As far as I understand, you want to receive choice input from user and validate it in this segment:
if (choice > 1 || choice < 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
Well, this condition doesn't supports what you've printed inside, this choice > 1 || choice < 3 condition always gets true. Also, you haven't prompted to take the entry from the user again.
You can fix this issue as below:
while (choice < 1 || choice > 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
choice = console.nextInt();
}
Then you're trying to make random choices for Computer. But you're selecting through upper bound and adding 1 to it. Why not set the bound to 1 more?
int comp = r.nextInt(4);
Then, finally, you're trying to compare the choice and the result. Where result was assigned -1 at the time of declaration and was never changed. That's why it'll never enter any if blocks and the Cwin and Uwin will always print 0. I bet you wanted comp here, in place of result. Also, I've tried to make the program more understandable to user while running.
if (choice == 1 && comp == 2) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 2 && comp == 3) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 3 && comp == 1) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 2 && comp == 1) {
Uwin++;
System.out.println("You win!");
return;
}
if (choice == 3 && comp == 2) {
Uwin++;
System.out.println("You win!");
return;
}
if (choice == 1 && comp == 3) {
Uwin++;
System.out.println("You win!");
return;
}
System.out.println("It's a draw!");
It will work as expected if you fix the aforementioned issues.
Note: I haven't refactored your code, I've just pointed out the problems and fixed it without modifying it much. It can be made lot more better than the current condition. Let's keep the topic for another day's question.
I modify your code somewhat.
You mention in a comment that you don't want to use an array and static variable.
so, I tried some different method hope It will help you.
It is fully working code
import java.util.*;
public class rockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome To Rock Paper scissors Game Type yes to continue or no for close.");
String YoN = input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
game();
} else if(YoN.equalsIgnoreCase("yes")) {
System.out.println("Thank You");
}else {
System.out.println("Enter valid input");
}
}
public static void game() {
int Uwin = 0;//user win count
int Cwin = 0;//computer win count
int tie = 0;//Tie count
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("Are you sure!!! Want to continue? Type yes or no.");
String YoN = input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
Scanner console = new Scanner(System.in);
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
int choice = console.nextInt();
int result = (int) (Math.random()*(3-1)) + 1;
if (choice < 1 || choice > 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
if((choice == 1 && result == 3) || (choice == 2 && result == 1) || (choice == 3 && result == 2)) {
System.out.println("Computer Choose"+result);
Uwin++;
}else if((choice == 1 && result == 2) || (choice == 2 && result == 3) || (choice == 3 && result == 1)) {
System.out.println("Computer Choose"+result
);
Cwin++;
}else {
System.out.println("Computer Choose"+result);
tie++;
}
} else if(YoN.equalsIgnoreCase("no")) {
System.out.println("Computer wins: " + Cwin + "\nUser wins: " + Uwin+"\nTie: "+tie);
System.out.println("Thank you");
break;
}else {
System.out.println("Enter valid input");
}
}
}
}
Track the score separately from the individual game
It looks you've written your game() method to play a single game of Rock, Paper, Scissors. In that case, you only need to return one value: who won that single game. Then your main method can keep track of the current scores and print out the totals after it's all done.
Consider an approach like the following:
import java.util.*;
public class rockPaperScissors {
public final static int USER_WON = 1; // Added these constants
public final static int COMPUTER_WON = 2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Uwin = 0;// user win count // Moved from `game()`
int Cwin = 0;// computer win count // Moved from `game()`
System.out.println("Play again? Type yes or no.");
String YoN = input.next();
if (YoN.equalsIgnoreCase("yes")) {
int winner = game(); // Modified this line
if (winner == USER_WON) { // Added this section
Uwin++;
} else {
Cwin++;
}
} else {
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
}
}
public static int game() { // Modified this line
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
Scanner console = new Scanner(System.in);
//// Truncating for brevity ////
if (choice == 3 && result == 1) {
return COMPUTER_WON; // Modified this line
}
if (choice == 2 && result == 1) {
return USER_WON; // Modified this line
}
//// Truncating for brevity ////
}
}
Notice that I moved the Uwin and Cwin variables out of game() and into your main method. Then I changed game() to return an integer instead of nothing (void) and replaced the Cwin++ and Uwin++ statements with a simple return COMPUTER_WON or return USER_WON based on the results of the rock, paper, scissors match. That return value can then be processed in your main method to keep a running total of how many games each player has won.
Use a class
If you're interested in trying something more advanced, consider creating an Object to encapsulate the two values you want to return.
For example, by storing both win counts in a simple Scoreboard object like the one below would enable you to return the two win counts at the same time and encapsulate the process of printing the scoreboard to the screen.
If you go this route, you'd have to make sure that all games reference the same Scoreboard. There are a variety of ways to do this from using a class variable, to passing the Scoreboard as a function parameter to the game() method, to moving all your logic for playing multiple games into the game() method. There are lots of options for you to try out and see which works best for you in this situation.
public class Scoreboard {
private int computerWins;
private int playerWins;
public Scoreboard() {
computerWins = 0;
playerWins = 0;
}
public void addComputerWin() {
computerWins++;
}
public void addPlayerWin() {
playerWins++;
}
#Override
public String toString() {
return "Scoreboard: "
+ "\n - Computer wins: " + computerWins
+ "\n - Player wins: " + playerWins;
}
}

while loop is skipping over my if/else statements

I have this while loop of a Rock Paper Scissors game and I have if/else if statements that tell you which player won, but the while loop is skipping it and going straight to the end of the loop where it asks if you want to play another game. How would I be able to change this?
Scanner scan = new Scanner(System.in);
String play = "";
System.out.print("Please enter Play if you want to play the game or anything else to Stop");
play = scan.nextLine();
while (play.equalsIgnoreCase("play")) {
System.out.println("Game " + gameCount + " Rock, Paper, Scissors - Play!");
System.out.print("Choose your weapon [R]ock, [P]aper, or [S]cissors: ");
String rps = scan.nextLine();
while (rps.equals('R') || rps.equals('P') || rps.equals('S')) {
System.out.println("You chose: " + rps);
}
int rand = (int)(Math.random() * 3);
String myMove = "";
if(rand == 0) {
myMove = "Rock";
}
else if(rand == 1) {
myMove = "Paper";
}
else {
myMove = "Scissors";
}
System.out.println("I chose: " + myMove);
if(rps.equals(myMove)) {
System.out.println("Tie!");
tieCount++;
}
else if(rps.equals('P') && myMove.equals("Scissors")) {
System.out.println("Scissors beats paper, a win for me!");
myCount++;
}
else if(rps.equals('S') && myMove.equals("Rock")) {
System.out.println("Rock beats scissors, a win for me!");
myCount++;
}
else if(rps.equals('R') && myMove.equals("Paper")) {
System.out.println("Paper beats rock, a win for me!");
myCount++;
}
else if(rps.equals('S') && myMove.equals("Paper")) {
System.out.println("Scissors beats paper, a win for you!");
userCount++;
}
else if(rps.equals('R') && myMove.equals("Scissors")) {
System.out.println("Rock beats scissors, a win for you!");
userCount++;
}
else if(rps.equals('S') && myMove.equals("Paper")) {
System.out.println("Paper beats rock, a win for you!");
userCount++;
}
gameCount++;
System.out.println("Please enter Play if you want to play the game again or anything else to Stop.");
play = scan.nextLine();
}
'''
Try this out
while (true) {
System.out.println("Insert question code:");
String question = scanner.nextLine();
if(question.equals("quit")){
break;
}
System.out.println("Insert answer code:");
String answer = scanner.nextLine();
if(answer.equals("quit")){
break;
}
}

trouble getting results from rock paper scissors code (java)

so when I run my code, it keeps saying that it is a tie because I think there is a problem in one of my methods.
Here is my whole code:
String userChoice = "";
String computerChoice = "";
System.out.println("Welcome to Rock, Paper, Scissors.");
System.out.println("The rules of the game are Rock breaks Scissors, "
+ "Scissors cut Paper, and Paper covers Rock. In this game, "
+ "the user will play against the computer.");
System.out.println("The legend for this game is: R = rock, P = paper,"
+ " and S = scissors.");
generateUserChoice();
generateComputerChoice();
determiningOutcome(userChoice, computerChoice);
repeatGame(userChoice, computerChoice);
}
public static String generateComputerChoice() {
String computerChoice = "";
int computerIntChoice;
Random generator = new Random();
computerIntChoice = generator.nextInt(3) + 1;
if (computerIntChoice == 1) {
computerChoice = "R";
} else if (computerIntChoice == 2) {
computerChoice = "P";
} else if (computerIntChoice == 3) {
computerChoice = "S";
}
System.out.println("The computer played " + computerChoice);
return computerChoice;
}
public static String generateUserChoice() {
String userChoice;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter your choice:");
userChoice = input.nextLine();
userChoice = userChoice.toUpperCase();
return userChoice;
}
public static void determiningOutcome(String userChoice, String computerChoice) {
if (userChoice.equals(computerChoice)) {
System.out.println("It is a tie!");
} else if (userChoice.equalsIgnoreCase("R") && computerChoice.equalsIgnoreCase("S")) {
System.out.println("Rock beats Scissors, you win!!");
} else if (userChoice.equalsIgnoreCase("P") && computerChoice.equalsIgnoreCase("R")) {
System.out.println("Paper beats Rock, you win!!");
} else if (userChoice.equalsIgnoreCase("S") && computerChoice.equalsIgnoreCase("P")) {
System.out.println("Scissors beats Paper, you win!!");
} else if (computerChoice.equalsIgnoreCase("R") && userChoice.equalsIgnoreCase("S")) {
System.out.println("Rock beats Scissors, you lose.");
} else if (computerChoice.equalsIgnoreCase("P") && userChoice.equalsIgnoreCase("R")) {
System.out.println("Paper beats Rock, you lose.");
} else if (computerChoice.equalsIgnoreCase("S") && userChoice.equalsIgnoreCase("P")) {
System.out.println("Scissors beats Paper, you lose.");
} else {
System.out.println("Sorry, invalid choice.");
}
}
public static int repeatGame(String userChoice, String computerChoice) {
int playAgain;
Scanner input = new Scanner(System.in);
System.out.println("Would you like to play again? 1 = yes and 2 = no");
playAgain = input.nextInt();
if (playAgain == 1) {
System.out.println("Would you like to play again? 1 = yes and 2 = no");
generateUserChoice();
generateComputerChoice();
determiningOutcome(userChoice, computerChoice);
}else {
System.out.println("Thank you for playing!!");
}
return playAgain;
}
}
however I think the problem is in the generateComputerChoice part of my code
Thanks in advance
The problem is that the userChoice and computerChoice is always been empty therefore it always a tie.
You need to assign your userChoice and computerChoice from the return value of the methods.
like this:
userChoice = generateUserChoice();
computerChoice = generateComputerChoice();

how to stop a loop in java if a value is incremented consecutively for three times?

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.

Adding a while loop to make a user input rock paper scissors game repeat until the user ends the game

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

Categories