This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
Hopefully this is a quick question. I'm making a simple rock paper scissors game. I make a random computer choice fine, and get the user's choice fine. But when I try to find who wins, it prints the last else in my else if block that is for invalid input.
It prints "Enter a valid choice" when a correct choice has been made.
import java.util.Random;
import javax.swing.JOptionPane;
public class JavaApplication4 {
public static void main(String[] args)
{
Random ranNums = new Random();
int comp = ranNums.nextInt(3);
String comp2;
String winner;
String user = JOptionPane.showInputDialog
(null, "Enter rock, paper, or scissors");
user.toLowerCase();
if(comp == 0)
comp2 = "rock";
else if(comp == 1)
comp2 = "paper";
else
comp2 = "scissors";
//Computer wins
if(comp2 == "rock" && user == "scissors")
winner = "The computer wins";
else if(comp2 == "paper" && user == "rock")
winner = "The computer wins";
else if(comp2 == "scissors" && user == "paper")
winner = "The computer wins";
//Tie game
else if(comp2 == "rock" && user == "rock")
winner = "It's a tie";
else if(comp2 == "paper" && user == "paper")
winner = "It's a tie";
else if(comp2 == "scissors" && user == "scissors")
winner = "It's a tie";
//User wins
else if(comp2 == "scissors" && user == "rock")
winner = "You win!";
else if(comp2 == "rock" && user == "paper")
winner = "You win!";
else if(comp2 == "paper" && user == "scissors")
winner = "You win!";
else
winner = "Enter a valid choice";
JOptionPane.showMessageDialog(null, "You picked " + user + "\n" +
"The computer picked " + comp2 + "\n" +
winner);
}
}
you can't use
comp == "paper"
to compare strings in java. You use
comp.equals("paper")
or if case doesn't matter
comp.equalsIgnoreCase("paper")
Don't compare Strings using ==. Use the equals or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
One way to simplify your code is to create a RockPaperScissors enum and give it its on compare method. Something like:
enum RockPaperScissors {
ROCK("Rock"), PAPER("Paper"), SCISSORS("Scissors");
private String text;
private static int[][] winMatrix = {{0, -1, 1}, {1, 0, -1}, {-1, 1, 0}};
private RockPaperScissors(String text) {
this.text = text;
}
#Override
public String toString() {
return text;
}
// can't use compareTo since it is a final method for enums
public int compareVs(RockPaperScissors other) {
int thisOrdinal = ordinal();
int otherOrdinal = other.ordinal();
return winMatrix[thisOrdinal][otherOrdinal];
}
}
Then to compare one enum vs. another, simply call its compareVs(...) method passing in the other enum.
So your huge if/else block would reduce down to:
// assuming that user and comp are RockPaperScissors variables
int result = user.compareVs(comp);
if (result == 1) {
System.out.println("You've won!");
} else if (result == 0) {
System.out.println("It's a tie!");
} if (result == -1) {
System.out.println("You've lost!");
}
If you are like me and you enjoy raw code:
import java.util.Random;
import javax.swing.JOptionPane;
public class JavaApplication4 {
public static void main(String[] args)
{
Random ranNums = new Random();
int comp = ranNums.nextInt(3);
String comp2;
String winner;
String user = JOptionPane.showInputDialog
(null, "Enter rock, paper, or scissors");
user.toLowerCase();
if(comp == 0)
comp2 = "rock";
else if(comp == 1)
comp2 = "paper";
else
comp2 = "scissors";
//Computer wins
if(comp2.equals("rock") && user.equals( "scissors"))
winner = "The computer wins";
else if(comp2.equals("paper") && user.equals( "rock"))
winner = "The computer wins";
else if(comp2.equals("scissors") && user.equals( "paper"))
winner = "The computer wins";
//Tie game
else if(comp2.equals("rock") && user.equals( "rock"))
winner = "It's a tie";
else if(comp2.equals("paper") && user.equals( "paper"))
winner = "It's a tie";
else if(comp2.equals("scissors") && user.equals( "scissors"))
winner = "It's a tie";
//User wins
else if(comp2.equals("scissors") && user.equals( "rock"))
winner = "You win!";
else if(comp2.equals("rock") && user.equals( "paper"))
winner = "You win!";
else if(comp2.equals("paper") && user.equals( "scissors"))
winner = "You win!";
else
winner = "Enter a valid choice";
JOptionPane.showMessageDialog(null, "You picked " + user + "\n" +
"The computer picked " + comp2 + "\n" +
winner);
}
}
Hope that helped!
You cannot compare string like this: if (comp2 == "rock")
You need to write: if ("rock".equals(comp2))
Related
I am trying to add an exit option to this code. Also, my results will not read correctly, and I am not sure what I am doing wrong. I've tried using a do while loop, but I can't seem to place it in the correct place.
//import Scanner Class
import java.util.Scanner;
import java.util.Random;
public class JavaMidterm {
public static void main(String[] args) {
String result = " ", symbola = " ", symbolb = " ";
Scanner s = new Scanner(System.in);
//prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
// read user choice
int choice=s.nextInt();
//Create random class object
Random random = new Random();
//Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if(choice == pick)
result = "It is a draw";
else {
if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick ==0)) || ((choice == 2) && (pick == 1)) )
result = "You won";
else
result = "You lose";
}
if(pick == 0)
symbola = "Scissor";
if(choice == 0)
symbolb = "Scissor";
//assigning symbols to the corresponding values
if(pick == 1)
symbolb = "Rock";
if(pick == 2)
symbola = "Paper";
if(choice == 2)
symbolb = "Paper";
System.out.println("The computer is" +
symbola + ". You are" + symbolb + ". " + result);
}
}
You can try my solution below. I have also included checking for invalid inputs. I also simplified the checking for your result.
//import Scanner Class
import java.util.Random;
import java.util.Scanner;
public class JavaMidterm {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Create random class object
Random random = new Random();
String[] choices = new String[] { "Scissor", "Rock", "Paper" };
int choice;
// prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
while (true) {
try {
String result = "";
// read user choice
choice = Integer.parseInt(s.nextLine());
if (choice < 0 || choice > 2) {
throw new Exception();
}
// Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if (choice == pick)
result = "It is a draw";
else if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick == 0))
|| ((choice == 2) && (pick == 1)))
result = "You won";
else
result = "You lose";
System.out.println("The computer is " + choices[pick] + ". You are " + choices[choice] + ". " + result);
System.out.print("Do you want to play again? Yes (0), No (1): ");
while (true) {
try {
// read user choice
choice = Integer.parseInt(s.nextLine());
if (choice < 0 || choice > 1) {
throw new Exception();
}
if (choice == 0)
System.out.print("Scissor (0), rock (1), paper (2): ");
break;
} catch (Exception e) {
System.out.println("Invalid input.");
System.out.print("Do you want to play again? Yes (0), No (1): ");
}
}
if (choice == 1) {
break;
}
} catch (Exception e) {
System.out.println("Invalid input.");
System.out.print("Scissor (0), rock (1), paper (2): ");
}
}
s.close();
}
}
I assume that you wish to end the game in case of a "win" and continue the game in case of "losing". Assuming that the code can be modified like below,
boolean isGoodToContinue = true;
while (isGoodToContinue) {
String result = " ", symbola = " ", symbolb = " ";
Scanner s = new Scanner(System.in);
// prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
// read user choice
int choice = s.nextInt();
// Create random class object
Random random = new Random();
// Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if (choice == pick)
result = "It is a draw";
else {
if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick == 0))
|| ((choice == 2) && (pick == 1))) {
result = "You won";
isGoodToContinue = false;
}
else {
result = "You lose";
isGoodToContinue = true;
}
}
I've written out all the code for an assignment for my programming class. The assignment requires us to create a program that allows the user to play rock paper scissors against a computer. We're required to have individual methods to obtain the computer's choice, the user's choice, check if the user's choice is valid, and also to determine the winner of the match. If a match doesn't end in a tie we need to print why the match was won, eg. "Scissors cuts Paper," and print who wins. Everything works properly, except when the user wins it's never counted or announced. For example instead of printing:
The computer's choice was rock. The user's choice was paper. Paper covers Rock. The user wins!
it prints:
The computer's choice was rock. The user's choice was paper. Paper covers Rock.
import java.util.Scanner;
import java.util.Random;
public class FinalRockPaperScissors {
//Computer's Choice
public static int computersChoice (int options) {
Random randGen = new Random();
int computerValue = randGen.nextInt(options)+1;
System.out.println(computerValue); //FOR TESTING ONLY
return computerValue;
}
//Player's Choice
public static int usersChoice () {
Scanner scnr = new Scanner(System.in);
System.out.print("Enter 1 for rock, 2 for paper, or 3 for scissors: ");
int userValue = scnr.nextInt();
if (isValid(userValue) == true) {
return userValue;
}
else {
userValue = 0;
return userValue;
}
}
//Check for valid user input
public static boolean isValid (int userInput){
if (userInput == 1 || userInput == 2 || userInput == 3) {
return true;
}
else {
return false;
}
}
//Checking winner
public static char determineWinner () {
char win;
int computerValue = computersChoice(3);
int userValue = usersChoice();
//print computer choices
if (computerValue == 1) {
System.out.println("The computer's choice was rock.");
}
else if (computerValue == 2) {
System.out.println("The computer's choice was paper.");
}
else if (computerValue == 3){
System.out.println("The computer's choice was scissors.");
}
//print user choices
if (userValue == 1) {
System.out.println("The user's choice was rock.");
}
else if (userValue == 2) {
System.out.println("The user's choice was paper.");
}
else if (userValue == 3){
System.out.println("The user's choice was scissors.");
}
//check who won
if (computerValue == 1) { //rock vs
if (userValue == 2) { //paper
System.out.println("Paper wraps Rock.");
return win = 'b';
}
else if (userValue == 3) { //scissors
System.out.println("Rock smashes Scissors.");
return win = 'a';
}
else if (userValue == 1){ //rock
return win = 'c';
}
else {
System.out.println("The user chose an invalid number. This round will be ignored.");
return win = 'd';
}
}
else if (computerValue == 2) { //paper vs
if (userValue == 2) { //paper
return win = 'c';
}
else if (userValue == 3) { //scissors
System.out.println("Scissors cuts Paper.");
return win = 'b';
}
else if (userValue == 1){ //rock
System.out.println("Paper wraps Rock.");
return win = 'a';
}
else {
System.out.println("The user chose an invalid number. This round will be ignored.");
return win = 'd';
}
}
else { //scissors vs
if (userValue == 2) { //paper
System.out.println("Scissors cuts Paper.");
return win = 'a';
}
else if (userValue == 3) { //scissors
return win = 'c';
}
else if (userValue == 1){ //rock
System.out.println("Rock smashes Scissors.");
return win = 'b';
}
else {
System.out.println("The user chose an invalid number. This round will be ignored.");
return win = 'd';
}
}
}
public static void main(String[] args) {
int userWins = 0;
int computerWins = 0;
int ties = 0;
int error = 0;
//for (int i = 0; i < 1; i++) { //5 for testing purposes
if (determineWinner() == 'a') {
System.out.println("The computer wins!");
System.out.println("");
computerWins++;
}
else if (determineWinner() == 'b') {
System.out.println("The user wins!");
System.out.println("");
userWins++;
}
else if (determineWinner() == 'c'){
System.out.println("The game is tied!");
System.out.println("");
ties++;
}
else {
error++;
}
//}
System.out.println("The number of ties is " + ties);
System.out.println("The number of user wins is " + userWins);
System.out.println("The number of computer wins is " + computerWins);
//output final winner
if (computerWins > userWins) {
System.out.println("Computer is the winner.");
}
else if (userWins > computerWins) {
System.out.println("User is the winner.");
}
else {
if (userWins == computerWins) {
System.out.println("User is the winner.");
}
else if (computerWins == ties) {
System.out.println("Computer is the winner.");
}
}
}
}
After some testing I've discovered that the problem may be with my userchoice() method. If I disable this method and give a set value for the user, everything works as it should. The problem is I don't know why it doesn't work, and as a result I can't fix it.
I think you're so new to Java and also let's start to show you your mistake in this code, you called determineWinner() multiple times which shouldn't be like that because you repeat the game four times to determine the result once, so you should call it once and get the returned value and check the value, like:-
char result = determineWinner(); //Play the game and get the result
// use it in conditions
if (result == 'a') {
System.out.println("The computer wins!");
System.out.println("");
computerWins++;
}
else if (result == 'b') {
System.out.println("The user wins!");
System.out.println("");
userWins++;
}
else if (result == 'c'){
System.out.println("The game is tied!");
System.out.println("");
ties++;
}
else {
error++;
}
In your main function You are calling determineWinner() every time you test your if condition. The proper way would be to store the returned value in a variable and then check if that variable is 'a', 'b' or 'c'. For example:
char result = determineWinner();
if (result == 'a') {
System.out.println("The computer wins!");
System.out.println("");
computerWins++;
}
First off, I'm pretty green when it comes to java. So, I'm making a rock paper scissors game with 2 classes and an object connecting the two. For some unknown reason, when I use the object, it cannot find the method im pointing to. The error is "cannot find symbol" and is in the first class where it is game.RockPaperScissors();
public class RPSRunner {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
char response;
//add in a do while loop after you get the basics up and running
out.print("type in your prompt [R,P,S] :: ");
String player = keyboard.nextLine();
RockPaperScissors game = new RockPaperScissors();
do {
game. **RockPaperScissor **(player);
} while (player == r || p || s);
}
}
and
public class RockPaperScissors {
String playChoice;
String compChoice;
Random random = new Random();
int rand = 0;
public RockPaperScissors() {
playChoice = " ";
compChoice = " ";
}
public RockPaperScissors(String player) {
setPlayers(player);
}
public void setPlayers(String player) {
playChoice = player;
rand = random.nextInt(3);
if (rand == 0) {
compChoice = "r";
}
if (rand == 1) {
compChoice = "p";
}
if (rand == 2) {
compChoice = "s";
}
System.out.println("player had " + playChoice);
System.out.println("computer had " + compChoice);
}
public String determineWinner() {
String winner = "";
if ((compChoice == "r") && (playChoice == "p")) ;
{
winner = "!Player wins << Paper covers Rock>>!";
}
if ((compChoice == "r") && (playChoice == "s")) ;
{
winner = "! Computer wins << Rock breaks Scissors >>!";
}
if ((compChoice == "p") && (playChoice == "r")) ;
{
winner = "! Computer wins << Paper covers Rock>>!";
}
if ((compChoice == "p") && (playChoice == "s")) ;
{
winner = "!Player wins << Scissors cuts paper >>!";
}
if ((compChoice == "s") && (playChoice == "p")) ;
{
winner = "! Computer wins << Scissors cuts paper >>!";
}
if ((compChoice == "s") && (playChoice == "r")) ;
{
winner = "!Player wins << Rock breaks Scissors >>!";
}
if (compChoice == playChoice) ;
{
winner = " !Tie << Both the computer and player have selected " + compChoice + " >>!";
}
return winner;
}
public String toString() {
String output = "";
return output;
}
}
Change
public RockPaperScissors(String player)
To
public void RockPaperScissors(String player)
The former is a constructor while the latter is a method. Also,there seems to be numerous other problems in your code(like the condition of the do...while loop,using == to compare Strings etc)
I was tasked with making a simple program that will play Rock-Paper-Scissors with the user. Unfortunately, when I try to run the program, my return(sentence+outcome) both returns null. I am new to using methods, so please explain what I am doing wrong here... Thank you!
package rockpaperscissors;
/**
*
* #author Owner
*/
import java.util.Scanner;
import java.io.IOException;
public class RockPaperScissors {
static int weaponChoice;
static int computerChoice;
static int tie = 0;
static int lose = 0;
static int win = 0;
static String outcome;
static String sentence;
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
Scanner userInput = new Scanner(System.in);
System.out.println(" =========================");
System.out.println("====ROCK=PAPER=SCISSORS====");
System.out.println(" =========================");
int playAgain = 1; //sets a play again function
do {
System.out.println("Please select your weapon.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
System.out.println("Choose wisely:");
String choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
do {
if (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3) {
System.out.println("Please choose again, grasshopper. There are only"
+ " three choices.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
}
} while (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3);
if (weaponChoice == 1) {
System.out.println("You have selected Rock as your weapon.");
} else if (weaponChoice == 2) {
System.out.println("You have selected Paper as your weapon.");
} else {
System.out.println("You have selected Scissors as your weapon.");
}
//Computer's Choice
computerChoice = 1 + (int) (Math.random() * ((3 - 1) + 1));
if (computerChoice == 1) {
System.out.println("The computer has chosen Rock.");
} else if (computerChoice == 2) {
System.out.println("The computer has chosen Paper.");
} else {
System.out.println("The computer has chosen Scissors.");
}
determineOutcome(outcome, sentence);
System.out.println(sentence+outcome);
System.out.println("==SCORES==");
System.out.println("WINS: " + win);
System.out.println("TIES: " + tie);
System.out.println("LOSSES: " + lose);
System.out.println("Press 1 to play again, or any other number to exit.");
String play = userInput.nextLine();
playAgain = Integer.parseInt(play);
} while (playAgain == 1);
}
public static String determineOutcome(String outcome, String sentence) {
sentence = "Your result is: ";
do {
if (weaponChoice == 1 && computerChoice == 1 || weaponChoice == 2 && computerChoice == 2 || weaponChoice == 3 && computerChoice == 3) {
tie++;
outcome = "TIE";
} else if (weaponChoice == 1 && computerChoice == 3 || weaponChoice == 2 && computerChoice == 1 || weaponChoice == 3 && computerChoice == 2) {
win++;
outcome = "You WON!";
} else {
lose++;
outcome = "You LOSE. Better luck next time?";
}
} while (lose <0 || win < 0 || tie < 0);
return(sentence+outcome);
}
}
To make this work, you'll need to replace
determineOutcome(outcome, sentence);
System.out.println(sentence+outcome);
with
String valueReturned = determineOutcome(outcome, sentence);
System.out.println(valueReturned);
because Java is pass by value, not pass by reference. That means that the determineOutcome method will work with its own copies of outcome and sentence, and not modify the versions that belong to the method that called it.
But also, the method is not actually using the two arguments you pass into it. It would be much less confusing if you just omit the parameters entirely, and change it to public static String determineOutcome() ... and declare String sentence; and String outcome; inside the method.
When calling a function that is returning a result you must either call the function within System.out.println() or assign the result to a variable which you then print.
Option 1:
String result = determineOutcome(outcome, sentence);
System.out.println(result);
or option 2:
System.out.println(determineOutcome(outcome, sentence));
In addition to the points other people made in their answers, it looks like your while loop is never being executed. The variables tie, win and lose are never less than 0, so the condition of the while loop is never true. You can try changing it to:
while (lose <= 0 || win <= 0 || tie <= 0);
But be warned, this will result in an infinite loop, so you may need to rethink your logic. You may not need a loop here, depending on what you're trying to do.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
The original prompt had us making a rock paper scissors game I think my code should work so far but I am getting the error "cannot find symbol" in line 64 when I try to track if a tie happens. Does anyone know what I am doing wrong?
import java.util.*;
public class RPS
{
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in);
Random myRandom = new Random();
boolean n = false;
System.out.println("Welcome to the Rock, Paper, Scissors game!!");
System.out.println("When you play, your choices are rock, paper, or scissors");
do
{
int compChoice = myRandom.nextInt(3);
String rock = "0";
String paper = "1";
String scissors = "2";
Integer.parseInt(rock);
Integer.parseInt(paper);
Integer.parseInt(scissors);
int compWins = 0;
int humanWins = 0;
int ties = 0;
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(myScanner.nextLine());
for(int i = 0; i < 3; i++)
{
if(choice == 0 && compChoice == 1)
{
System.out.println("I choose paper: I win this turn");
i++;
compWins++;
} else if(choice == 0 && compChoice == 2)
{
System.out.println("I choose scissors: You win this turn");
i++;
humanWins++;
} else if(choice == 1 && compChoice == 0)
{
System.out.println("I choose rock: You win this turn");
i++;
humanWins++;
} else if(choice == 1 && compChoice == 2)
{
System.out.println("I choose scissors: I win this turn");
i++;
compWins++;
} else if(choice == 2 && compChoice == 0)
{
System.out.println("I choose rock: I win this turn");
i++;
compWins++;
} else if(choice == 2 && compChoice == 1)
{
System.out.println("I choose paper: You win this turn");
i++;
humanWins++;
} else if(choice == compchoice)
{
System.out.println("This round is a tie");
i++;
ties++;
}
System.out.println("Score: me: " + compWins + "you: " + humanWins + "ties: " + ties);
}
if(compWins > humanWins)
{
System.out.println("Game over: I win!");
} else if(humanWins > compWins)
{
System.out.println("Game over: You win!");
}else
System.out.println("Game over: No one wins!");
System.out.print("Play again? (y/n)");
String ending = myScanner.nextLine();
if(ending == n)
{
n = true;
}
}
while(!n);
System.out.println("Thank you for playing!");
System.exit(0);
}
}
compchoice is not camel case. You declared it as compChoice.
You have 2 errors:
Java is case-sensitive, and you are using compchoice which is not declared anywhere. I guess you wanted to use compChoice instead:
} else if (choice == compChoice) {
You are comparing a String with a boolean in the line
if (ending == n) {
which is not a valid comparison because they are from different types. You may want to check your logic there.
Actually Java is case sinsitive, when you declared a variable you have to stick with that declaration.
So try to change :
} else if(choice == compChoice) // here you need to change compchoice to compChoice
{
System.out.println("This round is a tie");
i++;
ties++;
}
System.out.println("Score: me: " + compWins + "you: " + humanWins + "ties: " + ties);
Also You comparing a String with boolean, you need to parse the String to boolean then compare:
boolean ending = Boolean.valueOf(myScanner.nextLine());
if(ending == n)
{
n = true;
}