How to loop a JOptionsPane - java

Alright well, I semi figured it out with some searching, but now I have another issue
When the second box pops up and I click 'no' the first box still runs and if I cancel it I get an error. What am I doing wrong?
import javax.swing.*;
import java.util.*;
import java.util.Scanner;
public class RPS {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String input;
int user;
int computer;
while (true){//here we go
input = JOptionPane.showInputDialog("What'll it be? Rock, paper, or scissors?\n" +
"1 for rock, 2 for paper, and 3 for scissors: ",JOptionPane.YES_NO_OPTION);
user = Integer.parseInt(input);
Random randomnum = new Random ();
computer = randomnum.nextInt(3);
if (user == 1 && computer == 0){System.out.println ("You played Rock! You have tied");
JOptionPane.showMessageDialog(null, "Tie!");}
else if (user == 1 && computer == 1){System.out.println ("You have played Rock! You have lost");
JOptionPane.showMessageDialog(null, "Paper beats rock. You lose!");}
else if (user == 1 && computer == 2){System.out.println ("You have played Rock! You have won");
JOptionPane.showMessageDialog(null, "Rock beats scissors. You win!");}
else if (user == 2 && computer == 0){System.out.println ("You have played Paper! You have won");
JOptionPane.showMessageDialog(null, "Paper beats rock. You win!");}
else if (user == 2 && computer == 1){System.out.println ("You have played Paper! You have tied");
JOptionPane.showMessageDialog(null, "Tie!");}
else if (user == 2 && computer == 2){System.out.println ("You have played Paper! You have lost");
JOptionPane.showMessageDialog(null, "Scissors beats paper. You lose!");}
else if (user == 3 && computer == 0){System.out.println ("You have played Scissors! You have lost");
JOptionPane.showMessageDialog(null, "Rock beats Scissors. You lose!");}
else if (user == 3 && computer == 1){System.out.println ("You have played Scissors! You have won");
JOptionPane.showMessageDialog(null, "Scissors beats paper. You win!");}
else if (user == 3 && computer == 2){System.out.println ("You have played Scissors! You have tied");
JOptionPane.showMessageDialog(null, "Tie!");}
int n = JOptionPane.showConfirmDialog(null,"Would you like to play again?", "Confirmation",JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null,"Let's start");
} else {
JOptionPane.showMessageDialog(null,"Goodbye");
}
}
}
}

Put a return; statement after JOptionPane.showMessageDialog(null,"Goodbye");. otherwise it doesn't know to end the while loop.
The error when you press cancel would happen also if you chose cancel right away. It's because parseInt doesn't know how to read the resulting input. You should check the return value of showInputDialog to see that it's valid output. I would suggest checking for "1", "2", or "3" (or "rock", "paper", or "scizzors") instead of using parseInt, and then if it doesn't match any of them to come up with an error message of some sort.

Related

How do I count the playerwins for my code

Aye, so I have this assignment to make a rock, paper, scissor game. I did mostly everything right (maybe), but I can't figure out how to count the playerwins at the end when stopping a game of rock, paper, scissors. It is the one thing I am missing when running and stopping the code.
Playerwins are at the very bottom and the very top. The code is long as hell, but im new at coding and don't know how to make it less redundant.
import java.util.*;
import java.io.*;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner dodongo = new Scanner(System.in);
Random hamster = new Random();
System.out.println("Rock, Paper, Scissors!");
System.out.println("Press 1 for Rock, 2 for Paper, or 3 for Scissors");
while (!dodongo.hasNextInt(4)) {
System.out.println("Only numbers 1-3!");
System.out.println("Press 1 for Rock, 2 for Paper, or 3 for Scissors");
dodongo.next();
}
int player = dodongo.nextInt();
int rock = 1;
int paper = 2;
int scissors = 3;
int playerwins = 0;
System.out.println("YOU: Rock, Paper, Scissors! ");
System.out.println();
if ((player >= 0) && (player <= 1)) {
System.out.println("Rock!");
} else if ((player >= 1) && (player <= 2)) {
System.out.println("Paper!");
} else if ((player >= 2) && (player <= 3)) {
System.out.println("Scissors!");
}
System.out.println("Computer is playing...");
int shoot = -1;
System.out.println("COM: Rock, Paper, Scissors!");
do {
int keyblade = hamster.nextInt(3) + 1;
if ((keyblade >= 0) && (keyblade <= 1)) {
System.out.println("Rock!");
} else if ((keyblade >= 1) && (keyblade <= 2)) {
System.out.println("Paper!");
} else if ((keyblade >= 2) && (keyblade <= 3)) {
System.out.println("Scissors!");
}
shoot++;
if ((player == rock) && (keyblade == paper)) {
System.out.println("COM Win!");
System.out.println("You Lose! Paper beats rock, because a piece of paper can cover a rock!");
} else if ((player == rock) && (keyblade == scissors)) {
System.out.println("You Win! Rock beats scissors, because a rock can break a pair of scissors!");
} else if ((player == paper) && (keyblade == rock)) {
System.out.println("You Win! Paper beats rock, because a piece of paper can cover a rock!");
} else if ((player == paper) && (keyblade == scissors)) {
System.out.println("COM Win!");
System.out.println("You Lose! Scissors beats paper, because scissors can cut paper!");
} else if ((player == scissors) && (keyblade == rock)) {
System.out.println("COM Win!");
System.out.println("You Lose! Rock beats scissors, because a rock can break a pair of scissors!");
} else if ((player == scissors) && (keyblade == paper)) {
System.out.println("You Win! Scissors beats paper, because scissors can cut paper!");
} else {
System.out.println("Tie!");
}
playerwins++;
} while (shoot != 0);
System.out.println("Want to play again?(Press Y or N)");
String tryagain = dodongo.next();
if (tryagain.equalsIgnoreCase("Y")) {
main(null);
} else {
System.out.println("Adios...");
System.out.println("Total Wins: " + playerwins);
}
System.out.println();
}
}
I broke your code into methods. For the most part, this just organized the code a little better. I was able to use the writeInput method twice, so I also slightly reduced the duplication.
Once I created methods, the code in the main method was reduced enough that I could make a game loop using a do-while loop and remove the recursion.
I also corrected the playerwins count so it increments only when the player wins. The corrected code is in the compareInputs method.
Here's your code after adding methods.
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner dodongo = new Scanner(System.in);
Random hamster = new Random();
int playerwins = 0;
String tryagain;
do {
int player = readPlayerInput(dodongo);;
System.out.println("YOU: Rock, Paper, Scissors! ");
System.out.println();
writeInput(player);
System.out.println("Computer is playing...");
System.out.println("COM: Rock, Paper, Scissors!");
int keyblade = hamster.nextInt(3) + 1;
writeInput(keyblade);
playerwins += compareInputs(player, keyblade);
System.out.println("Want to play again?(Press Y or N)");
tryagain = dodongo.next();
} while (tryagain.equalsIgnoreCase("Y"));
System.out.println("Adios...");
System.out.println("Total Wins: " + playerwins);
System.out.println();
}
private static int readPlayerInput(Scanner dodongo) {
System.out.println("Rock, Paper, Scissors!");
System.out.println("Press 1 for Rock, 2 for Paper, or 3 for Scissors");
while (!dodongo.hasNextInt(4)) {
System.out.println("Only numbers 1-3!");
System.out.println("Press 1 for Rock, 2 for Paper, or 3 for Scissors");
dodongo.next();
}
return dodongo.nextInt();
}
private static void writeInput(int input) {
if ((input >= 0) && (input <= 1)) {
System.out.println("Rock!");
} else if ((input >= 1) && (input <= 2)) {
System.out.println("Paper!");
} else if ((input >= 2) && (input <= 3)) {
System.out.println("Scissors!");
}
}
private static int compareInputs(int player, int keyblade) {
int rock = 1;
int paper = 2;
int scissors = 3;
int playerWins = 0;
if ((player == rock) && (keyblade == paper)) {
System.out.println("COM Win!");
System.out.println("You Lose! Paper beats rock, because a "
+ "piece of paper can cover a rock!");
} else if ((player == rock) && (keyblade == scissors)) {
System.out.println("You Win! Rock beats scissors, because a "
+ "rock can break a pair of scissors!");
playerWins = 1;
} else if ((player == paper) && (keyblade == rock)) {
System.out.println("You Win! Paper beats rock, because a "
+ "piece of paper can cover a rock!");
playerWins = 1;
} else if ((player == paper) && (keyblade == scissors)) {
System.out.println("COM Win!");
System.out.println("You Lose! Scissors beats paper, because "
+ "scissors can cut paper!");
} else if ((player == scissors) && (keyblade == rock)) {
System.out.println("COM Win!");
System.out.println("You Lose! Rock beats scissors, because a "
+ "rock can break a pair of scissors!");
} else if ((player == scissors) && (keyblade == paper)) {
System.out.println("You Win! Scissors beats paper, because "
+ "scissors can cut paper!");
playerWins = 1;
} else {
System.out.println("Tie!");
}
return playerWins;
}
}
The first thing you need when you program any game is that you need a game loop, which runs the game until the user exits it. Interestingly, you opt for recursively calling main, which is also possible (although it could theoretically overload stack, which probably won't happen in this simple case but could be a real problem in a game that loops many times per second for a long time).
So the easiest fix would be to move the playerwins variable out of the main function (then you need to make it static as well) but the correct code that builds better habits for later work would be to use another while loop instead of recursively calling main.
Normally, beginners start with iterative code and discover recursion later, so it is nice that you discover it so early, but unfortunately that is not the correct case for it, but keep it in your pocket for other occasions.

while loop is skipping over my if/else statements

I have this while loop of a Rock Paper Scissors game and I have if/else if statements that tell you which player won, but the while loop is skipping it and going straight to the end of the loop where it asks if you want to play another game. How would I be able to change this?
Scanner scan = new Scanner(System.in);
String play = "";
System.out.print("Please enter Play if you want to play the game or anything else to Stop");
play = scan.nextLine();
while (play.equalsIgnoreCase("play")) {
System.out.println("Game " + gameCount + " Rock, Paper, Scissors - Play!");
System.out.print("Choose your weapon [R]ock, [P]aper, or [S]cissors: ");
String rps = scan.nextLine();
while (rps.equals('R') || rps.equals('P') || rps.equals('S')) {
System.out.println("You chose: " + rps);
}
int rand = (int)(Math.random() * 3);
String myMove = "";
if(rand == 0) {
myMove = "Rock";
}
else if(rand == 1) {
myMove = "Paper";
}
else {
myMove = "Scissors";
}
System.out.println("I chose: " + myMove);
if(rps.equals(myMove)) {
System.out.println("Tie!");
tieCount++;
}
else if(rps.equals('P') && myMove.equals("Scissors")) {
System.out.println("Scissors beats paper, a win for me!");
myCount++;
}
else if(rps.equals('S') && myMove.equals("Rock")) {
System.out.println("Rock beats scissors, a win for me!");
myCount++;
}
else if(rps.equals('R') && myMove.equals("Paper")) {
System.out.println("Paper beats rock, a win for me!");
myCount++;
}
else if(rps.equals('S') && myMove.equals("Paper")) {
System.out.println("Scissors beats paper, a win for you!");
userCount++;
}
else if(rps.equals('R') && myMove.equals("Scissors")) {
System.out.println("Rock beats scissors, a win for you!");
userCount++;
}
else if(rps.equals('S') && myMove.equals("Paper")) {
System.out.println("Paper beats rock, a win for you!");
userCount++;
}
gameCount++;
System.out.println("Please enter Play if you want to play the game again or anything else to Stop.");
play = scan.nextLine();
}
'''
Try this out
while (true) {
System.out.println("Insert question code:");
String question = scanner.nextLine();
if(question.equals("quit")){
break;
}
System.out.println("Insert answer code:");
String answer = scanner.nextLine();
if(answer.equals("quit")){
break;
}
}

Rock Paper Scissors does not work as expected [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm doing this Rock, Paper, Scissors Java program for an introduction to programming class and for some reason, the program is automatically terminating after the first user input.
I have a feeling it has to do with the
int randomNumber = rnd.nextInt(3) + 1;
statement but I'm not sure what I'm doing wrong here.
public static void main(String[] args) {
char userChar;
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
// Intro/directions/prompting for user input
System.out.println("Welcome to Rock, Paper, Scissors by Rancid!");
System.out.println("Choose R for Rock, P for Paper, S for Scissors, or Q to Quit, and press Enter: ");
userChar = sc.next().charAt(0);
// Prompting computer to generate a random number
int randomNumber = rnd.nextInt(3) + 1;
// If computer generates 1 (Rock)
if (randomNumber == 1) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Rock vs. Rock! It's a tie!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Paper covers Rock, you win!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Rock breaks Scissors, you lose!");
}
// If computer generates 2 (Paper)
if (randomNumber == 2) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Paper covers Rock, you lose!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Paper vs. Paper! It's a tie!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Scissors cuts Paper, you win!");
}
// If computer generates 3 (Scissors)
if (randomNumber == 3) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Rock breaks Scissors, you win!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Scissors cuts Paper, you lose!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Scissors vs. Scissors! It's a tie!");
}
// If player chooses to quit
if (userChar == 'q' || userChar == 'Q') {
System.out.println("Player chose to quit. Goodbye!");
}
// If player types an invalid character
else {
System.out.println("Invalid input! Please enter a valid character.");
}
}
}
}
}
}
Welcome to stackoverflow.
It seems like you're not using any loop inside your main method, so your program simply closes after it executed the last statement.
You want to add something like:
while (!"q".equals(userChar) && !"Q".equals(userChar)) {
System.out.println("Choose R for Rock, P for Paper, S for Scissors, or Q to Quit, and press Enter: ");
userChar = sc.next().charAt(0);
// Add your code where you check the randomNumber and the userChar here
}
Moreover you want to check your curly braces as the comments already state.

Rock Paper Scissors Lizards Spock

I need to print the number of user wins, losses, and ties in a program. It took me forever to resolve the looping issue, but I finally got it. I am new to Java, but have coded in HTML and other scripting languages before.
import java.io.InputStream;
import java.util.Random;
import java.util.Scanner;
public class RPSLS {
//AUTHOR: JOSEPH CLAY
//TODO make program continue until user chooses to stop.
//TODO then print # of user wins, losses, and ties.
public static void main(String[] args) {
//declare objects
String user;
String comp= "";
Random comprand;
String answer=null;
do
{
//scanner and random setup and imported
Scanner scan=new Scanner(System.in);
//Random gen=new Random();
//prompt to play game/instructions
System.out.println("Yo, let's play a game of Rock, Paper, Scissors, Lizard, Spock");
System.out.println("Please enter R for rock, P for paper, S for scissors, L for lizard, or V for Spock");
//User selection input
System.out.println("Pick your poison: ");
user=scan.next();
//Randomly generated # of 5
System.out.println();
comprand=new Random();
int x=comprand.nextInt(5)+1;
//translate random # to string
if(x==1)
comp="R";
else if(x==2)
comp="P";
else if(x==3)
comp="S";
else if(x==4)
comp="L";
else if(x==5)
comp="V";
//capitalize user selection
user=user.toUpperCase();
//print computer choice
System.out.println("Your adversary chose: "+comp);
//conditions of possible outcomes
//tie
if (user.equals(comp))
System.out.println("Tie!");
//if user enters r
else if (user.equalsIgnoreCase("R"))
if (comp.equals("S"))
System.out.println("Rock crushes scissors. You win!");
else if (comp.equals("P"))
System.out.println("Paper envelopes rock. You lose.");
else if (comp.equals("L"))
System.out.println("Rock destroys lizard. You win!");
else if (comp.equals("V"))
System.out.println("Spock crushes rock. You lose.");
//if user enters p
if (user.equalsIgnoreCase("P"))
if (comp.equals("R"))
System.out.println("Paper envelopes rock. You win!");
else if (comp.equals("S"))
System.out.println("Scissors cuts paper. You lose");
else if (comp.equals("L"))
System.out.println("Lizard eats paper. You lose.");
else if (comp.equals("V"))
System.out.println("Paper disproves Spock. You win!");
//if user enters s
if (user.equalsIgnoreCase("S"))
if (comp.equals("R"))
System.out.println("Rock crushes scissors. You lose.");
else if (comp.equals("P"))
System.out.println("Scissors cuts paper. You win!");
else if (comp.equals("L"))
System.out.println("Scissors eviscerates lizard. You win!");
else if (comp.equals("V"))
System.out.println("Spock vaporizes scissors. You lose.");
//if user enters l
if (user.equalsIgnoreCase("L"))
if (comp.equals("R"))
System.out.println("Rock crushes lizard. You lose.");
else if (comp.equals("P"))
System.out.println("Lizard eats paper. You win!");
else if (comp.equals("S"))
System.out.println("Scissors eviscerate lizard. You lose.");
else if (comp.equals("V"))
System.out.println("Lizard poisons Spock. You win!");
//if user enters v
if (user.equalsIgnoreCase("V"))
if (comp.equals("R"))
System.out.println("Spock crushes rock. You win!");
else if (comp.equals("P"))
System.out.println("Paper disproves Spock. You lose!");
else if (comp.equals("S"))
System.out.println("Spock vaporizes scissors. You win!");
else if (comp.equals("L"))
System.out.println("Lizard poisons Spock. You lose.");
System.out.println("Would you like to continue? (yes or no)");
answer = scan.next();
}
while(answer.equals("y"));
while (answer.equalsIgnoreCase("n"))
break;
}
}
Per your comments on your question, here is how you could implement keeping track of how many wins, losses, and ties the user has.
You declare variables to track each before you start your do loop. Since you want to count them I'd suggest a simple integer variable for each:
int wins = 0;
int losses = 0;
int ties = 0;
Then inside your loop you increment each counter when that situation occurs. For example:
if (comp.equals("R")){
System.out.println("Spock crushes rock. You win!");
wins++;
}
else if (comp.equals("P")){
System.out.println("Paper disproves Spock. You lose!");
losses++;
}
After your loop ends, i.e. after your while you then print these numbers.
while(answer.equals("y"));
System.out.println("You won "+wins+" times");
System.out.println("You lost "+losses+" times");
System.out.println("You tied "+ties+" times");
Lastly, some code review items for you. You generally never want to write code like this:
while(answer.equals("y"));
The reason is that if answer is null this will throw a NullPointerException at runtime. It's safer to write:
while("y".equals(answer));
In the code above "y" can never be null so you will never have a NullPointerException thrown by this code.
Secondly, hardcoding all of the possible scenarios is not the most efficient and maintainable way to write your program. Instead if you think in terms of objects (and you should since Java is an object oriented language) you could create an object to represent each possible choice and each object can contain others of its kind representing which choices will defeat it. Then you can simply do something like this:
if(userChoice.defeats(computerChoice)){
//handle user win here
}else if(computerChoice.defeats(userChoice){
//handle computer win here
}else{
//handle tie here
}
Hope this helps you!

how to stop a loop in java if a value is incremented consecutively for three times?

i'm new to java. i'm writing a sample of rock paper scissors game. the user input 0,1,2 for rock, paper, scissors respectively. the program randomly generated the result. i almost managed to get it work but the only thing i'm stuck at is how to STOP THE FOR LOOP IF ONE OF THE SIDE WINS CONSECUTIVELY FOR THREE TIMES.
THIS IS THE ORIGINAL QUESTION
Write a program that plays scissor-rock-paper game. The rule is that a scissor wins against a paper, a
rock wins against a scissor, and a paper wins against a rock. The program represent scissor as 0, rock
as 1, and paper as 2.
The game is to be played between the computer and a player. The program will prompt the user to
enter the number of rounds to win. For example, if the user enter 4 then the winner has to win at
least 3 out of the 4 rounds. If either party win 3 times consecutively, the game ends early without the
fourth round. If the user enter 5 rounds, the winner has to win at least 3 out of the 5 rounds. The
same rule of consecutive 3-wins also apply. After the user has entered the number of rounds, the
computer randomly generates a number between 0 and 2. The program then prompts the user to
enter a number 0, 1, or 2. After the last round (subject to the above mentioned early-winner-rule),
the program display a message indicating whether the computer or the user wins, loses, or draws.
THIS IS MY CODE.
package assignment1;
import java.util.Scanner;
import java.util.Random;
public class question1_9 {
// This program is used to play scissor-rock-paper game.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random random = new Random();
int scissor = 0, rock = 1, paper = 2, round, userinput,comprand, userresult = 0, compresult = 0, control,j,k;
// Variables used in this program is declared and initialized.
/* Number of rounds wished to be play are obtained from user. */
System.out.println("WELCOME TO ROCK PAPER SCISSOR GAME. ");
System.out.println("PLEASE ENTER THE NUMBER OF ROUND YOU WANT TO PLAY: ");
round = scan.nextInt();
control = (round/2)+1;
for(int i = 0; i<round; i++)
{
if (compresult == control | userresult == control)
{
break;
}
System.out.println("ROUND " + (i+1));
System.out.println("PLEASE ENTER:\n 0 for scissor \n 1 for rock \n 2 for paper \n");
userinput = scan.nextInt();
comprand = random.nextInt(3);
if (userinput == 0)
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("DRAW!!!");
i--;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("YOU WIN!!!");
userresult++;
}
}
else if (userinput == 1)
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("YOU WIN!!!");
userresult++;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("DRAW!!!");
i--;
}
}
else
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("YOU WIN!!!");
userresult++;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("DRAW!!!");
i--;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
}
}
if(compresult == userresult)
System.out.println("\n\nFINAL RESULT IS DRAW!!!");
else if (compresult > userresult)
System.out.println("\n\nFINAL RESULT IS COMPUTER WIN!!!");
else
System.out.println("\n\nFINAL RESULT IS YOU WIN!!!");
}
}
use break; statement when you want to get out of current loop.
At top of loop,
store the wins in an array
String[] results=new String[rounds];
store your results as "user" or "comp" for each round and at the end of loop do this
if((results[i].equals("user") && results[i-1].equals("user") && results[i-2].equals("user") || (results[i].equals("comp") && results[i-1].equals("comp") && results[i-2].equals("comp")))
{
break;
}
Like shreyas said, use a break statement when you want to exit a loop.
I would set compresult to zero whenever the player wins a round, and set userresult to zero whenever the computer wins. Then, at the top of the loop, right after the { add:
if(userResult == 3 || computerResult == 3 || round/2 > 10)
{
break;
}
Some code comes from shreyas's original post.

Categories