Rockpapergame with rounds and counter variables - java - java

I am creating a rock paper project which has the following requirement:
Continually plays rounds of rock, paper, scissors until one of the players wins three rounds. At that point, the program outputs the winner and the number of rounds it took them to win. If there is no winner after 10 rounds, the competition is declared a tie
Something seems to be missing which I am not quite able to understand or notice. How would I make my game stop after the rounds and declare a winner?
Note: No arrays, external libraries other than scanner, or any built-in methods of java allowed
This is my attempt:
import java.util.Scanner;
public class Rockpaper{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
String player1 = keyboard.next();
String player2 = keyboard.next();
String player = "Player1";
int round = 1;
boolean go = true;
boolean win = false;
while(go){
if (player1.equals("r") && player2.equals("p")){
win = true;
}
else if (player1.equals("p") && player2.equals("r")){
win = true;
}
else if (player1.equals("p") && player2.equals("s")){
win = true;
}
else if (player1.equals("s") && player2.equals("p")){
win = true;
}
else if (player1.equals("s") && player2.equals("r")){
win = true;
}
else if (player1.equals("r") && player2.equals("s")){
win = true;
}
else if (player1.equals("r") && player2.equals("r")){
win = false;
}
else if (player1.equals("p") && player2.equals("p")){
win = false;
}
else if (player1.equals("s") && player2.equals("s")){
win = false;
}
if (round < 5){
System.out.println(win+" after "+round+" rounds!");
go = false;
}else{
System.out.println("Tie - No winner after "+round+" rounds!");
}
if (player.equals("Player1"){
Player = "Player2";
}else{
Player = "Player1";
}
}
}
}
The problem I see is that there needs to be a separate variable that counts each of the win possibilities, for example, "win1" which would count the player1 win possibility and "win2" that would count the player2 wins. I am not quite sure about the rounds variable that would initially start counting the rounds up to 10 which is the maximum.
Sample input/output:

Currently you read the input only once, before the loop:
String player1 = keyboard.next();
String player2 = keyboard.next();
After every match, you should ask if players should continue playing. If so, then you must ask for their input again. This is, just move the "playerX" variable declaration and initialization inside the loop:
//comment/remove these
//String player1 = keyboard.next();
//String player2 = keyboard.next();
//inside the loop
while(go){
String player1 = keyboard.next();
String player2 = keyboard.next();
if (player1.equals("r") && player2.equals("p")){
/* rest of your code */
}
Also, this section:
if (round < 5){
System.out.println(win+" after "+round+" rounds!");
go = false;
}else{
System.out.println("Tie - No winner after "+round+" rounds!");
}
if (player.equals("Player1"){
Player = "Player2";
}else{
Player = "Player1";
}
}
It seems odd for two things:
round is never increased.
The else after round < 5 will be always executed, wrongly stating that there's a tie.
Reassigning Player variable for asking user input is not necessary. Instead, you could use 2 variables to store names of your players that are initialized before the game begins.
One more thing: instance of Scanner is Closeable, so each time you use it to read user input, you make sure that the instance is closed after is not needed anymore, in this case, at the end of the program.
More hints:
Reduce several if/else with the same output to a single if evaluation
You could make use of methods to ease game result.
With all this in mind, your code may look like this:
import java.util.Scanner;
public class RockPaperScizzorGame {
public static int getGameResult(String player1Move, String player2Move) {
int result = 0; //assume the game will be a tie
//player 2 wins
if (player1Move.equals("r") && player2Move.equals("p")
|| player1.equals("p") && player2.equals("s")
|| player1.equals("s") && player2.equals("r")
) {
result = 2;
}
//player 1 wins
if (player1.equals("p") && player2.equals("r")
|| player1.equals("s") && player2.equals("p")
|| player1.equals("r") && player2.equals("s")) {
result = 1;
}
//return the result: 0, 1 or 2
return result;
}
public static void main (String[] args) {
try (Scanner keyboard = new Scanner(System.in)) {
String player1Name = "Player 1";
String player2Name = "Player 2";
int round = 0;
boolean go = true;
int winsPlayer1 = 0;
int winsPlayer2 = 0;
while (go) {
System.out.println("Make your move " + player1Name + ": ");
String player1Move = keyboard.next();
System.out.println("Make your move " + player2Name + ": ");
String player2Move = keyboard.next();
int gameResult = getGameResult(player1Move, player2Move);
switch(gameResult) {
case 1:
winsPlayer1++;
break;
case 2:
winsPlayer2++;
break;
}
round++;
if (winsPlayer1 == 3) {
System.out.println(player1Name + " won after " + round + " rounds!");
go = false;
} else if (winsPlayer2 == 3) {
System.out.println(player2Name + " won after " + round + " rounds!");
go = false;
} else {
if (round == 5 && winsPlayer1 < 3 && winsPlayer2 < 3) {
System.out.println("Tie - No winner after "+round+" rounds!");
go = false;
}
}
} catch (IOException e) {
System.out.println("Issues when trying to accept user input.");
e.printStacktrace();
}
}
}
You can improve the code even more:
Use more methods to ease the code in main method.
Since your main loop depends more on a counter rather than a boolean flag, you may use a for loop rather than a while.
You may ask for user input for the name of the players.
You may create a class to encapsulate data of your players: name, currentMove, number of wins.

Problems with your code:
Not using separate variables for individual players.
Not putting input statements inside the loop as a result of which the input statements run only once.
Not changing the value of the variable, round but using its value in the condition, if (round < 5) which will always evaluate true if the value of round is not increased.
Solution
import java.util.Scanner;
public class Rockpaper {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int round = 1;
boolean go = true;
int player1Score = 0;
int player2Score = 0;
while (go && round <= 10) {
String player1 = keyboard.next();
String player2 = keyboard.next();
if (player1.equals("r") && player2.equals("p")) {
player2Score++;
} else if (player1.equals("p") && player2.equals("r")) {
player1Score++;
} else if (player1.equals("p") && player2.equals("s")) {
player2Score++;
} else if (player1.equals("s") && player2.equals("p")) {
player1Score++;
} else if (player1.equals("s") && player2.equals("r")) {
player2Score++;
} else if (player1.equals("r") && player2.equals("s")) {
player1Score++;
}
if (player1Score >= 3) {
System.out.println("Player1 wins " + " after " + round + " rounds!");
go = false;
}
if (player2Score >= 3) {
System.out.println("Player2 wins " + " after " + round + " rounds!");
go = false;
}
round++;
}
if (round > 10) {
System.out.println("Tie - No winner after " + (round - 1) + " rounds!");
}
}
}
First sample run:
p
r
r
s
s
s
r
r
p
r
Player1 wins after 5 rounds!
Second sample run:
p
p
p
r
r
r
s
s
p
p
s
s
s
s
p
p
r
p
s
p
Tie - No winner after 10 rounds!

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

Adding a loop to my game

I have a game that's running perfectly. I want to put a line of code that asks the player if they want to play again at the end of the game. I would also like to keep a score system for every player and computer win.
I'm having trouble with the input = Integer.parseInt(sc.nextInt()); line
import java.util.Scanner;
public class Sticks {
public static boolean whoStart(String choice) {
int ran = (int) (Math.random() * 2 + 1);
String ht = "";
switch (ran) {
case 1:
ht = "head";
break;
case 2:
ht = "tails";
}
if (ht.equals(choice.toLowerCase())) {
System.out.println("you start first");
return true;
} else {
System.out.println("computer starts first");
return false;
}
}
public static int playerTurn(int numberOfSticks) {
System.out.println(" \nthere are " + numberOfSticks + " sticks ");
System.out.println("\nhow many sticks do you wanna take? 1 or 2?");
Scanner in = new Scanner(System.in);
int sticksToTake = in.nextInt();
while ((sticksToTake != 1) && (sticksToTake != 2)) {
System.out.println("\nyou can only take 1 or 2 sticks");
System.out.println("\nhow many sticks do you wanna take?");
sticksToTake = in.nextInt();
}
numberOfSticks -= sticksToTake;
return numberOfSticks;
}
public static int computerTurn(int numberOfSticks) {
int sticksToTake;
System.out.println("\nthere are " + numberOfSticks + " sticks ");
if ((numberOfSticks - 2) % 3 == 0 || (numberOfSticks - 2 == 0)) {
sticksToTake = 1;
numberOfSticks -= sticksToTake;
} else {
sticksToTake = 2;
numberOfSticks -= sticksToTake;
}
System.out.println("\ncomputer took " + sticksToTake + " stick ");
return numberOfSticks;
}
public static boolean checkWinner(int turn, int numberOfSticks) {
int score = 0;
int input;
int B = 1;
int Y=5, N=10;
if ((turn == 1) && (numberOfSticks <= 0)) {
System.out.println("player lost");
return true;
}
if ((turn == 2) && (numberOfSticks <= 0)) {
System.out.println("player won");
score++;
return true;
}
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press (5) for Yes / (10) for No");
// ----- This line -----
input = Integer.parseInt(sc.nextInt());
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!");
}
}
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
System.out.println("choose head or tails to see who starts first");
String choice = in.next();
if (whoStart(choice) == true) {
do {
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
} else {
do {
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
}
}
}
The title of your question almost answered you what you need to add: a loop!
I suggest you to refactor your function main and extract all your game logic from it to be stored within a dedicated function for the sake of the readability. Let's call it startGame().
Your main is going to become shorter and can represent a good location to introduce this loop, such as:
public static void main(String[] a) {
boolean isPlaying = true;
Scanner in = new Scanner(System.in);
while(isPlaying) {
startGame();
// Your message to continue or stop the game
if(in.next().equalsIgnoreCase("No")) {
isPlaying = false;
}
}
}
I recommend you to use a boolean that is checked in your while loop rather than using a break statement, as it brings a better control flow in your application.
Just put everything in a while(true) loop and use a break; if they choose no. Something like:
static int playerPoints = 0;
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
while(true){
...
System.out.println("You have " + playerPoints + " points!")
System.out.println("Do you want to play again?");
if (!in.nextLine().toLowerCase().equals("yes")){
break;
}
}
}
Edit: ZenLulz's answer is better than this one, mainly because it encourages better programming practice. Mine works but isn't the best way to solve the issue.

Rock Paper Scissors simple java using methods

So my task today is to make a rock paper scissors game using methods. My first problem with my code is that I need it to ask the user if they want to play again or not. (y or n) Also, I need to implement scoring, 1 point if user wins, -1 if they lose, and for each time they play again add that score to total score. Any ideas on how to implement this? or what I need to change to my code. Also I am a rookie so sorry for the ugly formatting and feel free to critic every little detail, ill soak up all the information I can.
public static void main(String[] args){
boolean tie = true;
do{
String computer = computerChoice();
String user = userChoice();
tie = (computer.compareTo(user) == 0);
determineWinner(computer, user);
}while(tie);
}
public static String computerChoice( ){
Random rand = new Random();
int cinput = rand.nextInt(3)+ 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static String userChoice(){
Scanner sc = new Scanner (System.in);
String user = "default";
do{
System.out.println("choose your weapon(Paper,Scissors or Rock)");
user = sc.nextLine();
}
while (isValidChoice (user) == false);
return user;
}
public static boolean isValidChoice(String choice){
boolean status;
if (choice.compareTo("Rock")== 0)
status = true;
else if (choice.compareTo("Paper")== 0)
status = true;
else if (choice.compareTo("Scissors")== 0)
status = true;
else{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static boolean determineWinner(String computer, String user){
System.out.println (" Computer Choice: " + computer);
System.out.println ("Your Choice : " + user);
if (computer.compareTo( "Rock" ) == 0 && user.compareTo ("Scissors") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Scissors")== 0 && user.compareTo("Paper") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Rock") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Rock") == 0 && user.compareTo("Paper") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Scissors") == 0 && user.compareTo("Rock") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Scissors") == 0)
System.out.println (" You win!!");
else if (computer.compareTo(user) == 0 ){
System.out.println(" Tie! the game must be played again.");
return false;
}
return true;
}
}
a output that my professor gave us as an example is:
Choose your weapon!
1. Paper
2. Scissors
3. Rock
5
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose rock!
I have been vanquished!
We have matched wits 1 times, and your score is 1
Do you want to play again (y or n)? y
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose paper!
We are equally matched. You are a worthy adversary.
We have matched wits 2 times, and your score is 1
Do you want to play again (y or n)? n
Here is the finished code. I added two functions, one to call the actual game and one to check if the player wanted to play again. Also, there is the concluding sentence in the end
import java.util.Random;
import java.util.Scanner;
public class RPC
{
public static Scanner sc = new Scanner(System.in);
public static int score = 0;
public static int gameCount = 0;
public static void main(String[] args)
{
play();
while (playAgain())
{
play();
}
}
public static void play()
{
String computer = computerChoice();
String user = userChoice();
determineWinner(computer, user);
}
public static String computerChoice()
{
Random rand = new Random();
int cinput = rand.nextInt(3) + 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static boolean playAgain()
{
System.out.println("Play again?(y/n)");
String input = sc.nextLine();
if (input.toLowerCase().equals("y"))
{
return true;
} else if (input.toLowerCase().equals("n"))
{
return false;
} else
{
System.out.println("Invalid Input");
return playAgain();
}
}
public static String userChoice()
{
String user = "default";
do
{
System.out.println("choose your weapon(Paper,Scissors or Rock)");
user = sc.nextLine();
} while (!isValidChoice(user));
return user;
}
public static boolean isValidChoice(String choice)
{
boolean status;
if (choice.equals("Rock"))
status = true;
else if (choice.equals("Paper"))
status = true;
else if (choice.equals("Scissors"))
status = true;
else
{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static void determineWinner(String computer, String user)
{
gameCount++;
System.out.println(" Computer Choice: " + computer);
System.out.println("Your Choice : " + user);
if (computer.equals("Rock") && user.equals("Scissors"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Scissors") && user.equals("Paper"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Paper") && user.equals("Rock"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Rock") && user.equals("Paper"))
{
score++;
System.out.println(" You win!!");
}
if (computer.equals("Scissors") && user.equals("Rock"))
{
score++;
System.out.println(" You win!!");
}
if (computer.equals("Paper") && user.equals("Scissors"))
{
score++;
System.out.println(" You win!!");
} else if (computer.equals(user))
{
System.out.println(" Tie! the game must be played again.");
}
System.out.println("We have matched wits" + gameCount + "times, and your score is" + score);
return;
}
}

Monty Hall lets make a deal in JAVA using simpler operators and functions

So I've been working on this assignment for about 12 hours and have been unsuccessful in covering all the parameters. I was asked to make a program based off of Monty Hall "Lets make a deal" and asked to check each user input for validity up to the switching of doors;
I'm having the following issues:
if the user wants to switch doors after a zonk is revealed they're taken back to the main menu where they're asked to pick a door. then put in a continuous input loop
if the user's input is invalid at the switch doors scenario then the same problem as above happens
problem displaying the win percentage
problem when wanting to play the game again
please help, somewhat of a beginner so criticism is more than welcomed on all parts of the code.
System.out.println("WELCOME TO 'LETS MAKE A DEAL'");
System.out.println("Please Enter 'A' to Play, 'B' To Watch, or 'Q' To Quit");
Scanner input = new Scanner (System.in);
String choice = input.next();
boolean done = false;
double wins = 0;
double loses = 0;
double games = 0;
while (!done)
{
if(choice.equals("A"))
{
System.out.println("Please Choose a door:\n");
System.out.println("[1] [2] [3]\n");
System.out.println("Type '1', '2', or '3'");
if(input.hasNextInt())
{
int chosenDoor = input.nextInt();
if(chosenDoor <= 3 && chosenDoor > 0)
{
int prizeIs = (int) ((Math.random() * 3) + 1);
int finChoice = 0;
int zonkIs = 0;
while (prizeIs == chosenDoor)
{
zonkIs = (int) ((Math.random() * 3) + 1);
while (zonkIs == prizeIs)
{
zonkIs = (int) ((Math.random() * 3) + 1);
}
}
if (prizeIs == 1 && chosenDoor == 2)
{
zonkIs = 3;
}
else if (prizeIs == 1 && chosenDoor == 3 )
{
zonkIs = 2;
}
else if (prizeIs == 2 && chosenDoor == 1 )
{
zonkIs = 3;
}
else if (prizeIs == 2 && chosenDoor == 3 )
{
zonkIs = 1;
}
else if (prizeIs == 3 && chosenDoor == 1 )
{
zonkIs = 2;
}
else if (prizeIs == 3 && chosenDoor == 2 )
{
zonkIs = 1;
}
System.out.println("\nI Will Now Reveal A Zonk\n\nDoor [" + zonkIs + "]");
System.out.println("\nKnowing This, Would You Like To Switch Doors? ('Y' or 'N') ");
String decision = input.next();
if(decision.equals("Y"))
{
System.out.println("Pick A New Door (Not The One With A Zonk)");
chosenDoor = input.nextInt();
finChoice = chosenDoor;
System.out.println("\nWell Then\n\nThe Moment You've Been Waiting For\n");
System.out.println("The Prize is in\n\nDoor [" + prizeIs + "]");
if (prizeIs == finChoice || prizeIs == chosenDoor)
{
System.out.println("\nCONGRATUALTIONS!!!\nYOU WON!!!!!");
wins++;
games++;
}
else
{
System.out.println("\n..Sorry, You Lost.");
loses++;
games++;
}
System.out.println("\nWould You Like To Play Again? ('Y' or 'N')");
decision = input.next();
if(decision.equals("N"))
{
System.out.println("\nWell Thanks For Playing\nYour Win Percentage was ");
if(wins <= 0.0 || wins < loses)
{
double percentage = 0;
System.out.printf(percentage +"%");
}
else
{
double percentage = (wins-loses)/games * 100;
System.out.printf("%5.2f", percentage +"%");
}
done = true;
input.close();
}
else if(decision.equals("Y"))
{
System.out.println("*******************************");
}
else
{
System.out.println("Invalid Entry, Please Try Again ('Y' or 'N')");
}
}
else if(decision.equals("N"))
{
finChoice = chosenDoor;
System.out.println("\nWell Then\n\nThe Moment You've Been Waiting For\n");
System.out.println("The Prize is in\n\nDoor [" + prizeIs + "]");
if (prizeIs == finChoice || prizeIs == chosenDoor)
{
System.out.println("\nCONGRATUALTIONS!!!\nYOU WON!!!!!");
wins++;
games++;
}
else
{
System.out.println("\n..Sorry, You Lost.");
loses++;
games++;
}
System.out.println("\nWould You Like To Play Again? ('Y' or 'N')");
decision = input.next();
if(decision.equals("N"))
{
System.out.println("\nWell Thanks For Playing\nYour Win Percentage was ");
if(wins <= 0.0 || wins < loses)
{
double percentage = 0;
System.out.printf(percentage +"%");
}
else
{
double percentage = (wins-loses)/games * 100;
System.out.printf("%5.2f", percentage +"%");
}
done = true;
input.close();
}
else if(decision.equals("Y"))
{
System.out.println("*******************************");
}
else
{
System.out.println("Invalid Entry, Please Try Again ('Y' or 'N')");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again ('Y' or 'N')");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.");
input.next();
}
}
else if(choice.equals("B"))
{
}
else if(choice.equals("Q"))
{
done = true;
input.close();
}
else
{
System.out.println("Invalid Entry, Please Try Again..");
choice = input.next();
}
}
}
}
First, this part of the code makes no sense:
while (prizeIs == chosenDoor)
{
zonkIs = (int) ((Math.random() * 3) + 1);
while (zonkIs == prizeIs)
{
zonkIs = (int) ((Math.random() * 3) + 1);
}
}
The outer while loop here, since you change neither prizeIs nor chosenDoor inside, is going to be an endless loop.
Also, there is no point in choosing zonks out of the three doors, because after we have a prizeIs, there are only two zonks, which are the other doors. It would be best to use collections or array shuffles, I suppose, but if you are not allowed, you could list the possibilities.
if ( prizeIs == chosenDoor ) { // Note it's an if, not a while.
boolean chooseFirstZonk = Math.random() < 0.5; // 50% chance
switch ( prizeIs ) {
case 1:
if ( chooseFirstZonk ) {
zonkIs = 2;
} else {
zonkIs = 3;
}
break;
case 2:
if ( chooseFirstZonk ) {
zonkIs = 1;
} else {
zonkIs = 3;
}
break;
case 3:
if ( chooseFirstZonk ) {
zonkIs = 1;
} else {
zonkIs = 2;
}
break;
}
}
Then this if:
if (prizeIs == 1 && chosenDoor == 2)
becomes an else if to the above if.
Next, you have a bit of a misunderstanding about the game. Now that the zonk has been revealed, there are only two doors that are covered. If the user chooses to switch, he is not supposed to select a new door out of three. One is known to be a zonk, and one is known to be his previous choice which he chose to abandon. So when a user wants to switch, you are supposed to simply change chosenDoor to the unrevealed door.
If the original chosen door is the prize door, you are supposed to switch chosenDoor to the second zonk. So if prizeIs is 1, and so is chosenDoor, and zonkIs is 2, you change chosenDoor = 3. If zonkIs is 3, you do chosenDoor = 2.
If the original chosen door is not the prize door, you are supposed to assign chosenDoor = prizeIs - as the user chose a zonk, and you revealed the other zonk, so the only one remaining is the prize door.
So no user input is required in this case.
So you will need to change that large if-else. If the user chose to switch, you do the calculation. This if has no else, as when the user didn't say yes, he means to keep his original choice. At this point, check if chosenDoor == prizeIs, and calculate the percentages.
Calculations
First, you only need to keep two variables. Like wins and losses, or wins and games, or losses and games. You can always calculate losses as games - wins.
So always do games++, don't do losses at all, and do wins++ when the player wins.
Now calculating the success percentage does not require those ifs. wins cannot be less than zero. it also can't be greatar than games.
But what is important is to remember that if you divide an integer by an integer, you are going to get integer division. That is, 5/10 gives you zero, not 0.5, because it's not an integer.
So it's important to convert one of the numbers to double before you divide. One simple way to do this is to change the 100 to 100.0, and move it to the beginning:
double percentage = 100.0 * wins / games;
This way, 100.0 * wins automatically converts the value of wins to double. Therefore, when the result of it is divided by games, the value of games is also converted to double, and there is no integer division.

My java game isn't working

So i'm still a beginner but I managed to get this code but it didn't work like I wanted, my main problem is that every time I press 1 it resets the enemy instead of keeping the same one. I would really appreciate if someone could help me. So far I have only made writing 1 do something.
package Game;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();
System.out.println("Welcome to Dragon Heart");
System.out.println("1. Start");
System.out.println("2. Quit");
int input = 0, enemyhealth = 75, enemyattack = 15, playerhealth = 100, playerattack, random;
boolean enemydead = true, playerdead = false;
input = in.nextInt();
if (input == 1) {
System.out.println("Game started!");
while (0 != 1) {
if (enemydead = true) {
enemyhealth = r.nextInt(50) + 51;
enemyattack = r.nextInt(15) + 6;
System.out.println("An enemy appears, it has " + enemyhealth + " health points and " + enemyattack + " attack points");
} else {
System.out.println("The enemy now has " + enemyhealth + "health points");
}
System.out.println("1. Attack");
System.out.println("2. Defend");
System.out.println("3. Run away");
System.out.println("4. Do nothing");
input = in.nextInt();
if (input == 1) {
playerattack = r.nextInt(5) + 21;
random = r.nextInt(2) + 1;
enemyhealth = enemyhealth - playerattack;
if (random == 1) {
playerhealth = playerhealth - enemyattack;
}
if (enemyhealth <= 0) {
enemydead = true;
System.out.println("The enemy has been killed");
} else {
enemydead = false;
}
}
}
} else if (input == 2) {
System.out.println("Game quit.");
}
}
}
Your logic for defense away is dubious, but your problem is here:
if(enemydead = true)
You're reassigning enemydead to true every single time.
You really want to check if the enemy is dead, which is accomplished with this:
if(enemydead)
Further, you could clean up while (0 != 1) to be while(true) instead. However, you're going to need to include a break statement somewhere in that loop so that it's not an infinite loop like it is now.
Lastly, it's a good idea to have lower-case package names as opposed to upper-case package names.

Categories