Need exe file to open console - java

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

Related

Having to resubmit user choice over and over

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!

Rock Paper Scissors programme [closed]

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++;
}
**************************************************/

Choosing Between 2 games in one code

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.

Java Do While isn't working properly

Sorry I am new to this site so not sure how this will show up. I am trying to make a simple Rock, Paper, Scissors game. After the while statement, if R, P, S isn't entered, the program just does nothing. I want it to loop back to the question at the beginning so a right choice can be entered. Also, how would I enter a print statement like "Invalid Choice Please Retry"?
package rps.gameapp;
import java.util.Scanner;
public class RPSGameApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int randNum = (int) (Math.random() * 3);
do
{
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));
String compChoice = "";
switch (randNum)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer entered \"" + compChoice + "\".");
if (compChoice.equalsIgnoreCase(userChoice))
{
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase(userChoice)
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P"))
{
System.out.println("User Wins");
} else
{
System.out.println("User Loses");
}
System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();
} while (playAgain.equalsIgnoreCase("Y"));
System.out.println("Thanks for Playing!");
}
}
It looks like you forgot one do for your inner do while loop.
It should be :
do {
do {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P") && !userChoice.equalsIgnoreCase("R") && !userChoice.equalsIgnoreCase("S"));
...
} while (playAgain.equalsIgnoreCase("Y"));
Without that inner do (and the curly braces surrounding that loop's body), the inner loop becomes a while loop with an empty body.
Like Eran said, you need to wrap your do-while loop in another loop, that will keep asking user for correct input. This is fully working code. One thing that could be better is the message after user inputs wrong letter.
Edit: also make sure you draw random number for every iteration.
Edit 2: to change the message depending on user input you can introduce a new variable that will keep the track of number of times you asked user for correct input. If it is 0- it means user is asked the first time and we should print "Welcome" message. It is anything other than 0- you need to ask the user for correct input. After every round we assign zero to the variable again and the cycle repeats. I have implemented this change in the code. Note that this variable can also be a boolean.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int iterationNumber;
while (true) {
iterationNumber = 0;
do {
if (iterationNumber == 0) {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
} else {
System.out.println("Please enter valid letter.");
System.out.println("Pick R, P, or S.");
}
iterationNumber++;
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));
String compChoice = "";
int randNum = (int) (Math.random() * 3);
switch (randNum) {
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer entered \"" + compChoice + "\".");
if (compChoice.equalsIgnoreCase(userChoice)) {
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase("R")
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P")) {
System.out.println("User Wins");
} else {
System.out.println("User Loses");
}
System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();
if (playAgain.equalsIgnoreCase("N")) {
break;
}
iterationNumber = 0;
}
System.out.println("Thanks for Playing!");
}

trouble getting results from rock paper scissors code (java)

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

Categories