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++;
}
**************************************************/
Related
Hey guys having some trouble with a multi part question. I'm trying to get a game of rock paper scissors done, when i try to test the code using the playRound method I have to input my choice over and over again and then it just prints out draw, you are the winner and the computer is the winner over and over, can anyone tell me where im going wrong ?
import java.util.Scanner;
import java.util.Random;
/**
* A class that will play a game of rock paper scissors.
*
* #author (your name)
* #version (a version number or a date)
*/
public class RockPaperScissors
{
private Scanner reader;
private int yourScore;
private int computerScore;
private Random ran = new Random();
public RockPaperScissors()
{
reader = new Scanner(System.in);
yourScore = 0;
computerScore=0;
Random ran = new Random();
}
public void printPrompt()
{
System.out.println("Enter your choice, paper, rock or scissors >");
String userChoice = userChoice();
System.out.println();
System.out.println();
System.out.println("Enter your choice, paper, rock or scissors >"+ userChoice);
}
public final String userChoice()
{
String userChoice= reader.next();
return userChoice;
}
public String computerChoice()
{
String compMove = ("");
int cpuChoice = ran.nextInt(3);
switch(cpuChoice)
{
case 0:
{
compMove = ("rock");
break;
}
case 1:
{
compMove = ("paper");
break;
}
case 2:
{
compMove = ("scissors");
break;
}
}
return (compMove);
}
public String findWinner(String yourChoice, String computerChoice)
{
yourChoice = userChoice();
computerChoice = computerChoice();
String Winner= null;
if (yourChoice.equals(computerChoice))
{
Winner = ("draw");
}
if (yourChoice.equals("rock"))
{
if (computerChoice.equals("paper"))
{
computerScore++;
Winner = ("computer");
}
else if (computerChoice == "scissors")
{
yourScore++;
Winner = ("you");
}
}
if (yourChoice.equals("paper"))
{
if (computerChoice.equals("scissors"))
{
computerScore++;
Winner = ("computer");
}
else if (computerChoice.equals("rock"))
{
yourScore++;
Winner = ("you");
}
}
if (yourChoice.equals("scissors"))
{
if (computerChoice.equals("rock"))
{
computerScore ++;
Winner = ("computer");
}
else if (computerChoice.equals("paper"))
{
yourScore++;
Winner = ("you");
}
}
if (!yourChoice.equals("rock||paper||scissors"))
{
computerScore++;
Winner = ("computer");
}
return Winner;
}
public void playRound()
{
printPrompt();
String computerChoice=computerChoice();
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
String findWinner = findWinner(computerChoice,userChoice);
{
if (findWinner.equals("draw"));
System.out.println("This game is a draw");
if (findWinner.equals("you"));
System.out.println("You are the winner");
if (findWinner.equals("computer"));
System.out.println("The computer is the winner");
}
System.out.println("You have " + yourScore + "and the computer has "+ computerScore);
}
}
The semicolon at the end of your if statements means that the if statement is COMPLETE. The lines immediately following your if statements are then stand-alone, they do not "belong" to the if statements...which is why they always run.
Change:
if (findWinner.equals("draw"));
System.out.println("This game is a draw");
To:
if (findWinner.equals("draw"))
System.out.println("This game is a draw");
Or even better:
if (findWinner.equals("draw")) {
System.out.println("This game is a draw");
}
Any advice on how i can get my initial choice to be saved so I don't
have to keep typing it in ?
In findWinner(), you're calling userChoice() and computerChoirce() AGAIN. At that point, the values are already in the parameters that were passed in, so you don't need those. Comment them out or remove them:
public String findWinner(String yourChoice, String computerChoice)
{
// You don't need these two lines:
//yourChoice = userChoice();
//computerChoice = computerChoice();
// ... other existing code ...
}
Then, in playRound(), you are calling both printPrompt() and userChoice(), which each have their own input mechanism:
printPrompt();
String computerChoice=computerChoice();
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
I'd get rid of printPrompt() and just do:
// printPrompt();
String computerChoice=computerChoice();
System.out.print("Enter your choice, paper, rock or scissors >");
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
You have some broken logic in findWinner(). This does not do what you think it does:
if (!yourChoice.equals("rock||paper||scissors"))
{
computerScore++;
Winner = ("computer");
}
I think what you were trying to do is make the computer win if the user did not type in "rock", "paper", or "scissors"? If so, change your if statements to else if statements and add a final else block:
public String findWinner(String yourChoice, String computerChoice)
{
String Winner = "";
if (yourChoice.equals(computerChoice))
{
Winner = "draw";
}
else if (yourChoice.equals("rock"))
{
if (computerChoice.equals("paper"))
{
computerScore++;
Winner = "computer";
}
else if (computerChoice.equals("scissors"))
{
yourScore++;
Winner = "you";
}
}
else if (yourChoice.equals("paper"))
{
if (computerChoice.equals("scissors"))
{
computerScore++;
Winner = "computer";
}
else if (computerChoice.equals("rock"))
{
yourScore++;
Winner = "you";
}
}
else if (yourChoice.equals("scissors"))
{
if (computerChoice.equals("rock"))
{
computerScore ++;
Winner = "computer";
}
else if (computerChoice.equals("paper"))
{
yourScore++;
Winner = "you";
}
}
else // user did not type "rock", "paper", or "scissors"!
{
computerScore++;
Winner = ("computer");
}
return Winner;
}
Lastly, MAJOR bug, you SWAPPED the order of your parameters when you called findWinner().
Change:
String findWinner = findWinner(computerChoice, userChoice);
To:
String findWinner = findWinner(userChoice, computerChoice);
Hope that helps!
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;
}
}
}
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.
I am doing a project to make a user login, then ask the user to select which game to play, then write the code for the game. I have done everything apart from being able to choose to between the 2 games. Any tips on how to do this would greatly help!
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.io.InputStreamReader;
public class SkillsDemo31 {
private static boolean again = true;
private static int action;
public static void main(String[] args) throws IOException {
//***************************
//Login
//***************************
class User {
User (String username, String password)
{
this.username = username;
this.password = password;
}
String GetUsername() {return username;}
String GetPassword() {return password;}
private String username;
private String password;
}
String greeting = "Hello";
String username;
String password;
// Used to hold the instance of a user who successfully logged in
User loggedInUser = null;
// Create an empty list to hold users
List<User> listOfUsers = new ArrayList<>();
// Add 3 users to the list
listOfUsers.add(new User("Gerry","spintown"));
listOfUsers.add(new User("Evelyn","poker"));
listOfUsers.add(new User("Joan","bonus"));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("*** Welcome to the program ***\n");
System.out.println(greeting);
System.out.println("Please type your username :");
username = br.readLine();
System.out.println("Please type your password :");
password = br.readLine();
for (User user : listOfUsers)
{
if (user.GetUsername().equals(username))
{
if (user.GetPassword().equals(password))
{
loggedInUser = user;
// when a user is found, "break" stops iterating through the list
break;
}
}
}
// if loggedInUser was changed from null, it was successful
if (loggedInUser != null)
{
System.out.println("User successfully logged in: "+loggedInUser.GetUsername());
}
else
{
System.out.println("Invalid username/password combination");
}
//**********************************
//Choice of Games
//**********************************
again = true;
action = 0;
while (again)
{
System.out.println("Please type 1 for Rock, Paper, Scissors or 2 for Play pick up sticks:");
action = Integer.parseInt(br.readLine());
if (action == 1)
{
System.out.println("\nYou have chosen to play Rock, Paper, Scissors");
}
else if (action == 2)
{
System.out.println("\nYou have chosen to Play pick up sticks");
again = false;
}
//******************************
//Rock,Paper,Scissors
//********************************
Random rnd = new Random();
int input;
int score = 0;
int B = 1;
System.out.println("Pick 1,2, or 3 for:");
System.out.println("Rock (1), Paper(2), or Scissors (3)");
while (B != 0) {
// 1 = rock
// 2 = paper
// 3 = scissors
// N= Integer.parseInt(br.readLine())
int Rock = 1, Paper = 2, Scissor = 3;
input = Integer.parseInt(br.readLine());
int randomNumber = rnd.nextInt(3 - 1 + 1) + 1;
if (randomNumber == Rock) {
if (input == Rock) {
System.out.println("Rock Vs. Rock: Tie");
} else if (input == Paper) {
System.out.println("Paper Vs. Rock: You Win!");
System.out.println("Congratulations!");
score++;
} else if (input == Scissor) {
System.out.println("Scissors Vs. Rock: You Lose");
}
} else if (randomNumber == Paper) {
if (input == Rock) {
System.out.println("Rock Vs. Paper: You Loose");
} else if (input == Paper) {
System.out.println("Paper Vs. Paper: Tie");
} else if (input == Scissor) {
System.out.println("Scissors Vs. Paper: You Win");
System.out.println("Congratulations!");
score++;
}
} else if (randomNumber == Scissor) {
if (input == Rock) {
System.out.println("Rock Vs. Scissors: You Win");
System.out.println("Congratulations!");
score++;
} else if (input == Paper) {
System.out.println("Paper Vs. Scissors: You Loose");
} else if (input == Scissor) {
System.out.println("Scissors Vs. Scissors: Tie");
}
}
int Y=5, N=10;
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press(5) For Yes/(10) For No");
input = Integer.parseInt(br.readLine());
if(input==Y){
B=1;
System.out.println("Rock, Paper,Scissors");
}
else if(input==N)
{System.exit(0);
System.out.println("Have A Good Day!");
}
//***********************
//Pick Up Sticks
//***********************
Scanner scanner = new Scanner(System.in);
while (true) {
int numSticks = 21;
System.out.println("Would You Like to go first? (Yes/No)");
Scanner input1 = new Scanner(System.in);
String goFirst = input1.nextLine();
Scanner take = new Scanner (System.in);
int numToTake = 0;
int score2 = 0;
while (numSticks > 0) {
if (goFirst.equals("Yes") || goFirst.equals("yes")) {
System.out.println("There are " + numSticks + " sticks ");
System.out.println("How many sticks do you want to take (1 or 2)");
numToTake = take.nextInt();
if (numToTake > 2) {
numToTake = 2;
}
else if (numToTake < 1) {
numToTake = 1;
}
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println("You lose");
System.out.println("Your score is " + score );
}
else {
if((numSticks - 2) % 3 == 0 || numSticks - 2 == 0) {
numToTake = 1;
}
else {
numToTake = 2;
}
System.out.println("Computer takes " + numToTake + " sticks " );
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println(" You win ");
score++;
System.out.println("Your score is " + score );
}
}
}
else {
if((numSticks - 2) % 3 == 0 || numSticks - 2 == 0) {
numToTake = 1;
}
else {
numToTake = 2;
}
System.out.println("Computer takes " + numToTake + " sticks " );
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println("You win");
score++;
System.out.println("Your score is " + score );
}
else {
System.out.println("There are " + numSticks + " sticks ");
System.out.println("How many sticks do you want to take (1 or 2)");
numToTake = take.nextInt();
if (numToTake > 2) {
numToTake = 2;
}
else if (numToTake < 1){
numToTake = 1;
}
numSticks = numSticks - numToTake;
if(numSticks <0){
System.out.println("You win");
score++;
}
}
}
}
System.out.println("Do you want to play again, type (5) for yes or (10) for no");
if (scanner.nextLine().equals("10")) {
break;
}
}
}
}
}
You should create for every game a class and create a start method there to start the game based on your user input for example:
System.out.println("Please type 1 for game 1 or 2 for game2:");
action = Integer.parseInt(br.readLine());
if (action == 1)
{
System.out.println("\nYou have chosen to game 1");
Game1 game1 = new Game1();
game1.start();
}
else if (action == 2)
{
System.out.println("\nYou have chosen game 2");
Game2 game2 = new Game2();
game2.start();
}
This code is based on your code.
Bob, I just check through your code.
According to what I saw, my understanding of your question is that "After user login and selected the game type, both game would run subsequently, while you only want to run the game user chose".
If that is the case, then the solution is easy:
Take the games code parts out from the
while(again){
// In this block, only keeps your user choice code.
}
block. That block would be just for getting user's choice.
After that choice block, you get your users' choice from variable "action". Now you just need to add a if block as below:
if(action == 1){
// Put your Rock,Paper,Scissors game code here, as user chose 1
//******************************
//Rock,Paper,Scissors
//********************************
...
}else if(action == 2){
// Put your Pick Up Sticks game code here, as user chose 2.
//***********************
//Pick Up Sticks
//***********************
...
}
As you only want to run one game at a time, you need a "IF" condition to tell the code which game to run.
So just "IF" is enough, but separating the "Choice" part and "Game" part, from my opinion, would make the code more simpler and easier to be understood.
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);
}
}
}