I'm trying to get a random number using the Random().nextInt() function. I don't know if it's right or if my logic is messed up or not reading right. Also for loop isn't working the way that it's suppose to be working. Can you please help? I'm trying to finish an assignment for class since we started Java like last month.
//DECLARE VARIABLES
String rounds, userChooses;
Random computerChooses = new Random();
int round = 1;
int userChoice = 0;
final int ONE = 1;
final int TWO = 2;
final int THREE = 3;
int computerChoice = computerChooses.nextInt(3) + 1;
//ASK USER FOR NUMBER OF ROUNDS
rounds = JOptionPane.showInputDialog(null, "How many rounds do you want to play?");
round = Integer.parseInt(rounds);
//TRACK NUMBER OF ROUNDS
for (int x = 1; x <= round; x++) {
JOptionPane.showMessageDialog(null, "This is round " + x + ".");
//CREATE THE INPUT FOR THE USER
try {
//START GAME
userChooses = JOptionPane.showInputDialog(null, "Enter 1)rock, 2)paper, or 3)scissors!");
userChoice = Integer.parseInt(userChooses);
if (userChoice > 3 || userChoice < 1) {
throw new Exception();
}
} catch (Exception ex) {
JOptionPane.showInputDialog(null, "That wasn't a number!", "Error!", JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, "You have not entered correct number! Terminating program!");
System.exit(0);
}
if (userChoice == ONE) {
if (computerChoice == ONE) {
JOptionPane.showMessageDialog(null, "You tied the computer.\nYou chose: rock\nComputer chose: rock");
} else if (computerChoice == TWO) {
JOptionPane.showMessageDialog(null, "You lost!\nYou chose: rock\nComputer chose: paper");
} else if (computerChoice == THREE){
JOptionPane.showMessageDialog(null, "You won!\nYou chose: rock\nComputer chose: scissors");
}
} else if (userChoice == TWO) {
if (computerChoice == ONE) {
JOptionPane.showMessageDialog(null, "You won!\nYou chose: paper\nComputer chose: rock");
} else if (userChoice == TWO) {
JOptionPane.showMessageDialog(null, "You tied!\nYou chose: paper\nComputer chose: paper");
} else if (userChoice == THREE) {
JOptionPane.showMessageDialog(null, "You lost!\nYou chose: paper\nComputer chose: scissors");
}
} else if (userChoice == THREE) {
if (computerChoice == ONE) {
JOptionPane.showMessageDialog(null, "You lost!\nYou chose: scissors\nComputer chose: rock");
} else if (computerChoice == TWO) {
JOptionPane.showMessageDialog(null, "You won!\nYou chose: scissors\nComputer chose: paper");
} else if (computerChoice == THREE) {
JOptionPane.showMessageDialog(null, "You tied!\nYou chose: scissors\nComputer chose: scissors");
}
}
}
}
Every time I choose something, it says that the computer always chooses the rock option. Any idea?
Simply by using a Random object:
new Random().nextInt(3) + 1;
As for your for-loop, the closing brace should be put after your catch Exception-block and not after: JOptionPane.showMessageDialog(null, "This is round " + round + ".");
Here is something that seems to work better:
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class RockPaperScissors {
private static final int ROCK = 1;
private static final int PAPER = 2;
private static final int SCISSORS = 3;
private Random computerChooses = new Random();
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RockPaperScissors().play();
}
});
}
protected void play() {
String rounds;
String userChooses;
int round = 0;
int userChoice;
// CREATE THE INPUT FOR THE USER
try {
rounds = JOptionPane.showInputDialog(null, "How many rounds do you want to play?");
round = Integer.parseInt(rounds);
// CREATE COUNTER
for (int x = 0; x < round; x++) {
int computerChoice = computerChooses.nextInt(3) + 1;
JOptionPane.showMessageDialog(null, "This is round " + x + ".");
// START GAME
userChooses = JOptionPane.showInputDialog(null, "Enter 1)rock, 2)paper, or 3)scissors!");
userChoice = Integer.parseInt(userChooses);
String message = null;
switch (userChoice) {
case ROCK:
switch (computerChoice) {
case ROCK:
message = "You tied computer. You both chose rock";
break;
case PAPER:
message = "You win.";
break;
case SCISSORS:
message = "You loose";
break;
}
break;
case PAPER:
switch (computerChoice) {
case ROCK:
message = "You win.";
break;
case PAPER:
message = "You tied computer. You both chose paper";
break;
case SCISSORS:
message = "You loose";
break;
}
break;
case SCISSORS:
switch (computerChoice) {
case ROCK:
message = "You loose";
break;
case PAPER:
message = "You win";
break;
case SCISSORS:
message = "You tied computer. You both chose scissors";
break;
}
break;
}
JOptionPane.showMessageDialog(null, message);
}
} catch (Exception ex) {
JOptionPane.showInputDialog(null, "That wasn't a number!", "Error!", JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, "You have not entered correct number! Terminating program!");
System.exit(0);
}
}
}
Related
I am a student of 2 months so bear with me here.
I am trying to show my friend a Rock, Paper, Scissors game in action. I've successfully created RockPaperScissors.exe using Launch4j.
Now when I click the game's executable file I get the console to open. But when my friend tries to do so, he gets the console with no words in it, if he tries to type it closes.
Is it possible to have an executable file force the console up? Do I need to change some part of my code in order to have that happen?
Code is below in case I need to add something to make this work.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
/***** CONSTANT SECTION *****/
public static void main(String[] args)
{
/***** DECLARATION SECTION *****/
Scanner keyboard;
Random rndGen;
char computerChoice;
int playerScore, compScore;
int winner, compInt;
String name;
String userChoice;
/***** INITIALIZATION SECTION *****/
keyboard = new Scanner(System.in);
rndGen = new Random();
computerChoice = ' ';
winner = -1;
compInt = -1;
playerScore = 0;
compScore = 0;
/***** INTRO SECTION *****/
System.out.print("What is your name? ");
name = keyboard.next();
System.out.println("\nHi " + name + ".");
System.out.println("\nLet's play Rock, Paper, Scissors!");
System.out.println("Best out of 3 wins.");
/***** INPUT SECTION *****/
while (playerScore < 2 && compScore < 2)
{
System.out.print("\nEnter your choice. Type R for rock, P for paper, or S for scissors: ");
//takes a char entry and changes it into a string, upper cases the entry, and then take the first letter of the string
userChoice = keyboard.next();
userChoice = userChoice.toUpperCase();
while (!(userChoice.equals("R") || userChoice.equals("P") || userChoice.equals("S")))
{
System.out.println("Invalid entry.");
System.out.println("");
System.out.print("Enter your choice. Type R for rock, P for paper, or S for scissors: ");
userChoice = keyboard.next();
userChoice = userChoice.toUpperCase();
}
/***** PROCESSING SECTION *****/
compInt = rndGen.nextInt(3);
if (compInt == 0)
{
computerChoice = 'R';
}
else if (compInt == 1)
{
computerChoice = 'P';
}
else
{
computerChoice = 'S';
}
winner = RockPaperScissors.decideWinner(userChoice,computerChoice);
/***** OUTPUT SECTION *****/
System.out.printf(name + " chose %s%nComputer chose %c%n",userChoice,computerChoice);
switch(winner)
{
case 0: System.out.println("It's a tie!");
break;
case 1: System.out.println(name + " wins!");
playerScore = playerScore + 1;
break;
case 2: System.out.println("Computer won!");
compScore = compScore + 1;
break;
default: System.out.println("Invalid choice. Try again");
break;
}
System.out.println(name + ": " + playerScore + ", Computer: " + compScore);
}
if (playerScore > compScore)
{
System.out.println("\n" + name + " is the winner!!!");
}
else
{
System.out.println("\nSorry, the computer wins this time.");
}
keyboard.close();
System.out.println("Thanks for playing!");
}
/***** STATIC METHODS *****/
//Given two characters (R, P or S) determines //winner user rock paper scissors rules. Error check
//done in main
public static int decideWinner(String p1,char p2)
{
String combo;
combo = String.format("%s%c",p1,p2);
if ((combo.equals("RS")) || (combo.equals("PR")) || (combo.equals("SP")))
{
return 1;
}
else if ((combo.equals("RP")) || (combo.equals("PS")) || (combo.equals("SR")))
{
return 2;
}
else if ((combo.equals("PP")) || (combo.equals("SS")) || (combo.equals("RR")))
{
return 0;
}
else
{
return -1;
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have been frustrated with this code. The goal is to create a rock paper scissors game, best of 3. I have tried to make a "while" loop but I've got it all wrong and ended up scrapping it back to what I started with, a non-looping code.
If anyone can enlighten me how to make it loop until the computer or player gets a score of 3 wins, I would be so grateful!! Thank you so much
Sorry I should clarify, it needs to loop until the user or computer has 3 wins, so they rebattle until the user or computer reaches 3 wins
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main(String[] args)
{
Scanner key;
Random randGen;
char userChoice, computerChoice;
int winner, compInt;
int computerScore;
int userScore;
int scoreCounter;
/***** INITIALIZATION SECTION *****/
key = new Scanner(System.in);
randGen = new Random();
userChoice = ' ';
computerChoice = ' ';
//winner = -1;
compInt = -1;
computerScore = 0;
userScore = 0;
scoreCounter = 0;
System.out.println("What is your name?");
String name = key.nextLine();
System.out.println(name + " play rock, paper, or scissors with me!!");
/***** INPUT SECTION *****/
System.out.println("Please enter R for rock, P for paper, or S for scissors:");
userChoice = key.next().toUpperCase().charAt(0);
//key.close();
/***** PROCESSING SECTION *****/
compInt=randGen.nextInt(3);
if (compInt == 0)
{
computerChoice = 'R';
}
else if (compInt == 1)
{
computerChoice = 'P';
}
else if (compInt == 2)
{
computerChoice = 'S';
}
winner = RockPaperScissors.decideWinner(userChoice,computerChoice);
/***** OUTPUT SECTION *****/
System.out.printf("Player: %c%nComputer: %c%n", userChoice, computerChoice);
switch (winner)
{
case 0:
System.out.println("It's a tie!");
System.out.println(name + ": " + userScore + ", Computer:" + computerScore );
break;
case 1:
System.out.println("You won!");
userScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore );
break;
case 2:
System.out.println("Computer won!");
computerScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore );
break;
default:
System.out.println("Invalid choice, try again.");
break;
}
//System.out.println("Thanks for playing!);
}
/***** STATIC METHODS *****/
/**Description: given two characters (R,P, or S) determines winner using rock
* paper rules. Assume input is valid and error checking is done in main
* programme. **/
public static int decideWinner(char p1,char p2)
{
String combo;
combo = String.format("%c%c", p1, p2);
switch(combo)
{
case "RS":
case "PR":
case "SP":
return 1;
case "RP":
case "PS":
case "SR":
return 2;
case "RR":
case "PP":
case "SS":
return 0;
}
return -1;
}
}
/***************************************************
while(userScore == 3)
{
System.out.println("You won the game" +name+ "! Congratulations");
scoreCounter++;
}
while(computerScore == 3)
{
System.out.println("Sorry " +name+ ", Computer won...");
scoreCounter++;
}
**************************************************/
Try splitting your code in methods that each have their own task, that way u can more easily lay out and control the behaviour of your program. E.g. in the case of user input, you can recursively call the method in case of invalid input.
For the while loop, I simply added a counter that increases after every game, until 3.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
private static int totalGames = 0;
public static void main(String[] args)
{
Scanner key;
Random randGen;
char userChoice, computerChoice;
int winner;
int computerScore;
int userScore;
/***** INITIALIZATION SECTION *****/
key = new Scanner(System.in);
randGen = new Random();
computerChoice = ' ';
//winner = -1;
computerScore = 0;
userScore = 0;
System.out.println("What is your name?");
String name = key.nextLine();
System.out.println(name + " play rock, paper, or scissors with me!!");
while(totalGames < 3) {
userChoice = getUserChoice(key, false);
/* PROCESSING SECTION */
computerChoice = getComputerChoice(computerChoice, randGen.nextInt(3));
winner = RockPaperScissors.decideWinner(userChoice, computerChoice);
totalGames++;
/* OUTPUT SECTION */
System.out.printf("Player: %c%nComputer: %c%n", userChoice, computerChoice);
switch (winner) {
case 0:
System.out.println("It's a tie!");
System.out.println(name + ": " + userScore + ", Computer:" + computerScore);
break;
case 1:
System.out.println("You won!");
userScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore);
break;
case 2:
System.out.println("Computer won!");
computerScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore);
break;
default:
System.out.println("Invalid choice, try again.");
break;
}
}
//System.out.println("Thanks for playing!);
}
private static char getComputerChoice(char computerChoice, int compInt) {
if (compInt == 0)
{
computerChoice = 'R';
}
else if (compInt == 1)
{
computerChoice = 'P';
}
else if (compInt == 2)
{
computerChoice = 'S';
}
return computerChoice;
}
private static char getUserChoice(Scanner key, boolean retry) {
char userChoice;
/* INPUT SECTION */
if(retry)
System.out.println("You entered an invalid input, please try again...");
System.out.println("Please enter R for rock, P for paper, or S for scissors:");
try {
userChoice = key.next().toUpperCase().charAt(0);
if(userChoice != 'R' && userChoice != 'P' && userChoice != 'S')
return getUserChoice(key, true);
} catch (Exception e){
return getUserChoice(key, true);
}
return userChoice;
}
/***** STATIC METHODS *****/
/**Description: given two characters (R,P, or S) determines winner using rock
* paper rules. Assume input is valid and error checking is done in main
* programme. **/
public static int decideWinner(char p1,char p2)
{
String combo;
combo = String.format("%c%c", p1, p2);
switch(combo)
{
case "RS":
case "PR":
case "SP":
return 1;
case "RP":
case "PS":
case "SR":
return 2;
case "RR":
case "PP":
case "SS":
return 0;
}
return -1;
}
}
/***************************************************
while(userScore == 3)
{
System.out.println("You won the game" +name+ "! Congratulations");
scoreCounter++;
}
while(computerScore == 3)
{
System.out.println("Sorry " +name+ ", Computer won...");
scoreCounter++;
}
**************************************************/
I'm trying to write a RockPaperScissors game for my Java class but I'm having trouble with my code. When it runs, sometimes it outputs the wrong thing and sometimes it is correct.
For example when the user enters P the computer is either supposed to answer with Tie, My Point, or Your Point, and then under it will say what each of us played. But often it will say some thing like "Your Point!" "R beats R".
import java.util.Scanner;
public class RockPaperScissors
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int tie = 0;
int win = 0;
int loss = 0;
String playerChoice;
System.out.println(RockPaperScissors.getComputerChoice());
while (true)
{
System.out.println();
System.out.print("(R)ock, (P)aper, (S)cissors, or quit: ");
playerChoice = input.nextLine();
if (playerChoice.equalsIgnoreCase("quit")) break;
else
//switch statement
if (playerChoice.equalsIgnoreCase(
RockPaperScissors.getComputerChoice()))
{
System.out.println("Tie!");
tie++;
}
else if ((playerChoice.equalsIgnoreCase("R") &&
RockPaperScissors.getComputerChoice().equals("S")) ||
(playerChoice.equalsIgnoreCase("P") &&
RockPaperScissors.getComputerChoice().equals("R")) ||
(playerChoice.equalsIgnoreCase("S") &&
RockPaperScissors.getComputerChoice().equals("P")))
{
System.out.println("Your Point!");
System.out.println(playerChoice + " beats "
+ RockPaperScissors.getComputerChoice());
win++;
}
else if ((playerChoice.equalsIgnoreCase("R") &&
RockPaperScissors.getComputerChoice().equals("P")) ||
(playerChoice.equalsIgnoreCase("P") &&
RockPaperScissors.getComputerChoice().equals("S")) ||
(playerChoice.equalsIgnoreCase("S") &&
RockPaperScissors.getComputerChoice().equals("")))
{
System.out.println("My Point!");
System.out.println(RockPaperScissors.getComputerChoice()
+ " beats " + playerChoice);
loss++;
}
else
{
System.out.println("Invalid Input!");
}
}
System.out.println();
System.out.println("You won " + win + " times.");
System.out.println("You lost " + loss + " times.");
System.out.println("We tied " + tie + " times.");
}
public static String getComputerChoice ()
{
int compChoiceInt;
String compChoice;
compChoiceInt = (int) (Math.random() * 3);
switch (compChoiceInt)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
default:
compChoice = "Invalid Input";
System.out.println("Invalid Input.");
break;
}
return compChoice;
}
You're calling getComputerChoice() many times in your code that decides if the user wins, loses, or ties. That can result in several different possible outcomes to each round because each one of those method calls results in a new choice being randomly generated. Instead of calling that method several times, declare a variable and call it just once, before you compare it to the player's choice.
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 have my app class for the game Rock, Paper, Scissors. My problem is if I win two times or the computer wins two times I need the game to stop generating but it keeps going one more time. How can I rectify this?
import javax.swing.JOptionPane;
public class RockPaperScissorsApp
{
public static void main(String args[])
{
String player1, winner;
int player2, gamesPlayed = 1, player1Wins = 0, player2Wins = 0;
do
{
RockPaperScissors myRock = new RockPaperScissors();
player1 = JOptionPane.showInputDialog(null,
"Please enter your choice, Rock, Paper or Scissors");
myRock.setPlayer1(player1);
myRock.compute();
winner = myRock.getWinner();
player2 = myRock.getPlayer2();
if(winner.equals("Player 1"))
{
if(player2 == 1)
{
JOptionPane
.showMessageDialog(null,
"Congratulations, you have beaten the computer! The computer chose Rock");
}
else if(player2 == 2)
{
JOptionPane
.showMessageDialog(null,
"Congratulations, you have beaten the computer! The computer chose Paper");
}
else
{
JOptionPane
.showMessageDialog(null,
"Congratulations, you have beaten the computer! The computer chose Scissors");
}
player1Wins = player1Wins + 1;
}
else if(winner.equals("Player 2"))
{
if(player2 == 1)
{
JOptionPane
.showMessageDialog(null,
"Hard Luck, you have been beaten by the computer! The computer chose Rock");
}
else if(player2 == 2)
{
JOptionPane
.showMessageDialog(null,
"Hard Luck, you have been beaten by the computer!The computer chose Paper");
}
else
{
JOptionPane
.showMessageDialog(null,
"Hard Luck, you have been beaten by the computer! The computer chose Scissors");
}
player2Wins = player2Wins + 1;
}
else if(winner.equals("draw"))
{
if(player2 == 1)
{
JOptionPane.showMessageDialog(null,
"It was a draw this time! The computer chose Rock");
}
else if(player2 == 2)
{
JOptionPane
.showMessageDialog(null,
"It was a draw this time! The computer chose Paper");
}
else
{
JOptionPane
.showMessageDialog(null,
"It was a draw this time! The computer chose Scissors");
}
gamesPlayed = gamesPlayed + 0;
}
else
{
JOptionPane.showMessageDialog(null,
"You have entered an invalid option");
gamesPlayed = gamesPlayed - 1;
}
if(player1Wins == 2)
{
JOptionPane.showMessageDialog(null, "You win");
gamesPlayed = gamesPlayed + 2;
}
else if(player2Wins == 2)
{
JOptionPane.showMessageDialog(null, "He wins");
gamesPlayed = gamesPlayed + 2;
}
if((gamesPlayed == 2) || (gamesPlayed == 3))
{
JOptionPane.showMessageDialog(null, "The score is "
+ player1Wins + " for player1 and " + player2Wins
+ " for player2");
}
gamesPlayed = gamesPlayed + 1;
}
while(gamesPlayed <= 3);
}
}
Change your while loop condition:
while(player1Wins < 2 && player2Wins < 2)
Also, I would advise against using magic numbers; this is more maintainable:
public static final int VICTORY_THRESHOLD = 2;
.
.
.
while(player1Wins < VICTORY_THRESHOLD
&& player2Wins < VICTORY_THRESHOLD)
Also, consider creating an Enum for ROCK,PAPER,SCISORS. Then consider making a Comparator that takes the two Enums and returns -1 for losses, 0, for draw, and 1 for win.
public Enum RPS {
ROCK(),PAPER(),SCISSORS();
public int compare(RPS that) {
if(this==that)
return 0;
switch(this) {
case ROCK: return that==RPS.PAPER ? -1 : 1;
case PAPER: return that==RPS.SCISSORS ? -1 : 1;
case SCISSORS: return that==RPS.ROCK ? -1 : 1;
default: return null; /* never reached */
}
}
public String toString() {
switch(this) {
case ROCK: return "Rock";
case PAPER: return "Paper";
case SCISSORS: return "Scissors";
default: return null; /* never reached */
}
}
}
Using an Enum would make your conditional code much cleaner:
RPS player1Choice = RPS.ROCK;
RPS player2Choice = RPS.SCISSORS;
int result player1Choice.compare(player2Choice); /* 1 */
if(result == 0)
System.out.println("Draw, you both chose "+player1Choice);
else
System.out.println("You "+ (result > 0 ? "won" : "lost") +
" with "+player1Choice+
"\nThe computer chose"+player2Choice);
if(result != 0)
result > 0 ? ++player1Wins : ++player2Wins;
++gamesPlayed;
You said do... while(gamesPlayed <= 3) which means after 3 games have been played, the statement is still true, so it goes ahead and loops again.
To fix this, you can either change that 3 to a 2 or change the <= sign to a < sign.