output after first cycle in a while loop - java

My question is not about general game algorithm. When i answer "true" to the question "Do you want to continue? Enter true or false.", program outputs:
"Player one, throw your shape(rock, paper, scissors)!
Player two, throw your shape(rock, paper, scissors)!"
So i can enter values in first cycle but not in second. How can i fix it? Thanks.
code:
public static void main(String[] args) {
String playerOne;
String playerTwo;
Scanner myScan = new Scanner(System.in);
boolean playAgain = true;
do
{
System.out.println("Player one, throw your shape(rock, paper, scissors)! ");
playerOne = myScan.nextLine();
System.out.println("Player two, throw your shape(rock, paper, scissors)! ");
playerTwo = myScan.nextLine();
if (playerOne.equals("scissors") && playerTwo.equals("rock"))
{
System.out.println("Player one lost! Playr two won!");
}
else if (playerOne.equals("scissors") && playerTwo.equals("paper"))
{
System.out.println("Player one won! Player two lost!");
}
else if (playerOne.equals("rock") && playerTwo.equals("paper"))
{
System.out.println("Player one lost! Player two won!");
}
else if (playerOne.equals("rock") && playerTwo.equals("scissors"))
{
System.out.println("Player one won! Player two lost!");
}
else if (playerOne.equals("paper") && playerTwo.equals("scissors"))
{
System.out.println("Player one lost! Player two won!");
}
else if (playerOne.equals("paper") && playerTwo.equals("rock"))
{
System.out.println("Player one won! Player two lost!");
}
System.out.println("Do you want to continue? Enter true or false.");
playAgain = myScan.nextBoolean();
}while(playAgain);
}
}

This is because the Scanner only reads the boolean you request with nextBoolean and nothing else, not even the following line ending. The line ending then remains in the input stream and is returned as an empty line when the loop comes around and you ask for nextLine.
What you'll want to do instead is to read a complete line instead of just a boolean for playAgain, and interpret that manually (suggestedly with something like myScan.nextLine().equals("yes")).

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

Java rock paper scissor printing the statements oddly

So here i am trying to create a program that takes an input as an int and then plays a game of Rock paper scissors. It seems to want to reprint statements that it shouldn't be and is skipping printing statements as well. I would love some assistance if possible. I have tried setting up print statements everywhere but it has just been more confusing.
import java.util.Scanner;
public class RPSS{
//Main method
public static void main(String[ ] argc)
{
System.out.println("Lets play rock paper scissors");
Scanner tnt = new Scanner(System.in);
String computerHand; // string variable for computer choice
String userHand; // string variable for user choice
//
String answer = "";
while (!a
nswer.equals("No") && (!answer.equals("no"))){
userHand = userHand();
computerHand = computerHand();
System.out.println("The User picks " + userHand + " " );
System.out.print("The Computer picks " + computerHand );
String winner = getWinner(computerHand, userHand);
System.out.println(winner);
System.out.println("play again?");
answer = tnt.next();
}
//Condition for the do-while loop
}
public static String userHand(){ //method for users choice in the game
//prints message to user giving them choices
System.out.println(" ");
System.out.println("1. Rock ");
System.out.println("2. Paper ");
System.out.println("3. Scissors ");
int userChoice; // user choice variable in this method
Scanner tnt = new Scanner(System.in); // creates instance of scanner class
userChoice = tnt.nextInt(); //reads user input
return getChoice(userChoice); //returns user choice to userChoice
}
public static String computerHand() //method for computer generated choice
{
int computernum = 1 + (int)(Math.random() * (( 2) +1));
return getChoice(computernum);
}
public static String getChoice(int num) //method recieving both computer hand and user hand
{
// if statements to place the correct choice
String choice = "";
if (num == 1){
choice = "Rock";
}
else if(num == 2){
choice = "Paper";
}
else if(num == 3){
choice = "Scissors";
}
return choice;
}
// Method determing the winner
public static String getWinner(String computerChoice, String userChoice)
{
computerChoice = computerHand(); //places computerChoice variable in computerhand
userChoice = userHand(); //does same for user choice
String winner="";
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println("The computer wins");
return winner;
}
else if (userChoice.equals("Paper") && computerChoice.equals("Scissors")){
System.out.println(" The computer wins");
return winner;
}
else if (userChoice.equals("Scissors") && computerChoice.equals("Rock")){
System.out.println(" The computer wins ");
return winner;
}
else if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println(" The computer wins ");
return winner;
}
else if(userChoice.equals(computerChoice))
{
System.out.println(" There is no winner");
return " ";
}
else{
return winner;
}
}
}
The first problem is that userhand() and computerHand() are being called twice per "round", once at the beginning of the while loop inside the main method and once at the beginning of the getWinner() method. Elimination of the calls at the beginning of the getWinner() method should solve the repeats.
The 2nd Problem is that instead of modifying the value of winner inside the getWinner() method before returning it, you are you are simply outputting the message via println(). an example of fixing this would be converting this:
if (userChoice.equals("Rock") && computerChoice.equals("Paper"){
System.out.println("The computer wins");
return winner;
}
to this:
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
winner = "The computer wins";
return winner;
}
another minor issue is the fact that
userChoice.equals("Rock") && computerChoice.equals("Paper")
is checked twice, id just remove the entire if else block based around the
2nd check of it
Lastly i would treat the final else clause as the player wins one and set winner to something like " The player wins "

Rerun main method if an invalid response is given?

So I made this rock paper scissors game a while ago using Java and I found a little bug I forgot to fix when I showed it to my friend today. Basically, the code takes a user input (i.e rock, paper, or scissors) and if their input does not equal rock, paper, or scissors, the main while loop is broken and the game is stopped.
How can I make it so that not only does it break the loop, but restarts it as well? I want to do this so that when someone gives an invalid input it automatically restarts so the player doesn't need to run the program all over again.
Here's the code for my main class:
public class rps {
public static void main(String []args){
boolean gameRunning = true;
while(gameRunning) {
System.out.println("Do you choose rock, paper, or scissors?");
UserChoice userInput = new UserChoice();
String userChoice = userInput.userDecide();
if(userChoice != "rock" || userChoice != "paper" || userChoice != "scissors") {
System.out.println("'" + userChoice + "'" + " is not a valid choice.");
System.out.println("Please choose between rock, paper, or scissors.");
gameRunning = false;
break;
// this is where I want to restart the function
}
System.out.println("You threw: " + userChoice);
ComputerInput computerChoice = new ComputerInput();
String computerInput = computerChoice.computerDecide();
System.out.println("Computer threw: " + computerInput);
CompareChoices compareResults = new CompareChoices();
gameRunning = compareResults.compare(userChoice, computerInput);
}
}
};
UPDATE
I figured out a few of the problems thanks to some help from the nice people on here. I used && instead of || (which is dumb because I originally used && anyways -_-), I used the "continue" statement instead of break, I removed gameRunning = false;, and I changed the way userChoice was compared to the valid responses.
Instead of comparing it to Strings like "rock" and "paper", I created an array
(String validChoices[] = {"rock", "paper", "scissors"};) which holds the valid responses. Then I compared userChoice to the indices of the array.
Here is my new code:
public class rps {
public static void main(String []args){
boolean gameRunning = true;
while(gameRunning) {
System.out.println("Do you choose rock, paper, or scissors?");
UserChoice userInput = new UserChoice();
String userChoice = userInput.userDecide();
String validChoices[] = {"rock", "paper", "scissors"};
if(!userChoice.equals(validChoices[0]) && !userChoice.equals(validChoices[1]) && !userChoice.equals(validChoices[2])) {
System.out.println("'" + userChoice + "'" + " is not a valid choice.");
System.out.println("Please choose either rock, paper, or scissors.");
continue;
}
System.out.println("You threw: " + userChoice);
ComputerInput computerChoice = new ComputerInput();
String computerInput = computerChoice.computerDecide();
System.out.println("Computer threw: " + computerInput);
CompareChoices compareResults = new CompareChoices();
gameRunning = compareResults.compare(userChoice, computerInput);
}
}
};
Thanks everyone!
Do not set gameRunning to false, to not use break, use continue, which will ignore the rest of the loop and start the loop again.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
A couple of problems. setting your loop condition to false and breaking leaves no way to restart the loop. Also, as #resueman hinted at. Use .equals() instead of == for comparing strings. My suggestion is to put the error checking inside another while loop.
while(!userChoice.equals("rock") && !userChoice.equals("paper") && !userChoice.equals("scissors")) {
System.out.println("Your choice was invalid, try again");
userChoice = userInput.userDecide();
}
Also, you should maybe declare some of this stuff outside your while loop (I am thinking of your ComputerInput, UserInput and CompareChoices objects).

How to compare a String with an integer?

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

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.

Categories