Recently having learned how to create classes, objects, methods within those classes, how to access them from the main method, and why this is important so you're not always having to rewrite code/create chunky lines of code/save memory/etc., I ran into a bit of a problem.
So, I made a simple program of Rock Paper Scissors. Essentially, each time the program is run, the program takes user input -- assigns it to a variable, assigns a random number to another variable, and compares the two inputs using multiple if statements to decide an outcome. This is where my problem lies.
I was told that a class and methods tied to it are usually very broad, yet I feel like my method used to compare the two variables is too chunky, and could be reduced/condensed to a much simpler and efficient code.
I don't know how to achieve this. I'm not sure if adding more variables would be the way to go, thus making the comparisons simpler or something, or perhaps taking away some things/adding new types of code, etc. The point is, I want to make this code less chunky and more effective.
In the code, I have two ways of getting the exact values. I have your typical if statements, but I also made a switch statement. Both get me the same results, but I just thought that a switch statement would be easier to read.
ALSO, I realize that classes and methods probably aren't useful when making a Rock Paper Scissors game of this simplicity, but I just wanted to get the practice in and what not.
Here's my code:
along with the website you can run it on: https://repl.it/#ANGELRAMIREZ6/Rock-Paper-Scissors-UPGRADED
import java.util.Scanner;
import java.util.Random;
class Main {
public static void main(String[] args) {
action object = new action();
System.out.println("\nYou will now play Rock Paper Scissors with a Computer.");
object.getUserChoice();
object.getComputerChoice();
object.compareChoices();
}
}
class action {
Scanner sc = new Scanner(System.in);
Random rand = new Random();
int computerChoice;
int userChoice;
int getUserChoice() {
System.out.println("\nDo you choose (0)Rock, (1)Paper, (2)Scissors?");
userChoice = sc.nextInt();
return userChoice;
}
int getComputerChoice() {
computerChoice = rand.nextInt(2);
return computerChoice;
}
/*
void compareChoices() {
//IF YOU PICK ROCK
if (userChoice == 0) {
if (computerChoice == 1) {
System.out.println("You lose!\nYou picked rock and the computer picked paper.");
}
if (computerChoice == 2) {
System.out.println("You win!\nYou picked rock and the computer picked scissors.");
}
if (computerChoice == 0) System.out.println("It's a draw! You both picked rock!");
}
//IF YOU PICK PAPER
if (userChoice == 1) {
if (computerChoice == 0) {
System.out.println("You win!\nYou picked paper and the computer picked rock.");
}
if (computerChoice == 2) {
System.out.println("You lose!\nYou picked paper and the computer picked scissors.");
}
if (computerChoice == 1) System.out.println("It's a draw! You both picked paper!");
}
//IF YOU PICK SCISSORS
if (userChoice == 2) {
if (computerChoice == 1) {
System.out.println("You win!\nYou picked scissors and the computer picked paper.");
}
if (computerChoice == 0) {
System.out.println("You lose!\nYou picked scissors and the computer picked rock.");
}
if (computerChoice == 2) System.out.println("It's a draw! You both picked scissors!");
}
}
*/
void compareChoices() {
switch (userChoice) {
//IF YOU PICK ROCK
case 0:
if (computerChoice == 1) {
System.out.println("You lose!\nYou picked rock and the computer picked paper.");
}
if (computerChoice == 2) {
System.out.println("You win!\nYou picked rock and the computer picked scissors.");
}
if (computerChoice == 0) System.out.println("It's a draw! You both picked rock!");
break;
//IF YOU PICK PAPER
case 1:
if (computerChoice == 0) {
System.out.println("You win!\nYou picked paper and the computer picked rock.");
}
if (computerChoice == 2) {
System.out.println("You lose!\nYou picked paper and the computer picked scissors.");
}
if (computerChoice == 1) System.out.println("It's a draw! You both picked paper!");
break;
//IF YOU PICK SCISSORS
case 2:
if (computerChoice == 1) {
System.out.println("You win!\nYou picked scissors and the computer picked paper.");
}
if (computerChoice == 0) {
System.out.println("You lose!\nYou picked scissors and the computer picked rock.");
}
if (computerChoice == 2) System.out.println("It's a draw! You both picked scissors!");
break;
}
}
}
honestly although its a little bit long but its readable and for me code readability is so important. but if you want to make it little cleaner(and more readable) there are some suggestions.
instead of (0)Rock, (1)Paper, (2)Scissors it would be better to use an enum instead. it will be much more easier for human to read.
also you can take your win/lose messages there. this will make further changes much easier because you know where they are.
in your switch statement instead of using multiple if, make a method which takes 2 parameters( e.g userChoice - AIChoice ) and then returns who has won. i mean instead of comparing them right inside of switch, take them somewhere else and just replace those ifs with method call.
i hope it help you :)
Related
I started learning to program in java two/three days ago and decided to try and program a simple rock paper scissors game.
it wont run and i think that i either didn't include some important code or that this whole thing is just garbage.
thanks for help!
public class Game {
public static void main(String[] args) {
String personPlay; //User's play; either R, P or S
String computerPlay = ""; //Computer's play, R, P or S as well
int computerInt; //randomly generated number to etermine computers play
String response;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
System.out.prinln("Let's play Rock, Paper, Scissors!\n" + "Enter a move: \n" + "R = Rock, P = Paper, S = Scissors");
System.out.println();
computerInt = generator.nextInt(
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
System.out.println("Rock crushes Scissors! You win!");
else if (personPlay.equals("S"))
if (computerPlay.equals("P"))
System.out.println("Scissors cut Paper! You win!");
else if (personPlay.equals("P"))
if (computerPlay.equals("R"))
System.out.println("Paper wraps Rock! You win!");
else if (personPlay.equals("R"))
if (computerPlay.equals("P"))
System.out.println("Paper wraps Rock! You lose!");
else if (personPlay.equals("P"))
if (computerPlay.equals("S"))
System.out.println("Scissors cut Paper! You lose!");
else if (personPlay.equals("S"))
if (computerPlay.equals("R"))
System.out.println("Rock crushes Scissors! You lose!");
else System.out.println("Invalid user imput, please try again!");
}
}
I believe this answers your question:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
String personPlay; //User's play; either R, P or S
String computerPlay = ""; //Computer's play, R, P or S as well
String response;
Scanner scan = new Scanner(System.in);
System.out.println("Let's play Rock, Paper, Scissors!\n" + "Enter a move: \n" + "R = Rock, P = Paper, S = Scissors");
System.out.print("Player > ");
personPlay = scan.nextLine();
System.out.print("Computer > ");
String options [] = {"R","P","S"};
computerPlay = options[(int)(Math.random()*3)];
System.out.println(computerPlay);
if (personPlay.equals(computerPlay)) {
System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
if (computerPlay.equals("P")) {
System.out.println("Paper wraps Rock! You lose!");
}
else if (computerPlay.equals("S")) {
System.out.println("Rock crushes Scissors! You win!");
}
}
else if (personPlay.equals("P")) {
if (computerPlay.equals("R")) {
System.out.println("Paper wraps Rock! You win!");
}
else if (computerPlay.equals("S")) {
System.out.println("Scissors cut Paper! You lose!");
}
}
else if (personPlay.equals("S")) {
if (computerPlay.equals("R")) {
System.out.println("Rock crushes Scissors! You lose!");
}
else if (computerPlay.equals("P")) {
System.out.println("Scissors cut Paper! You win!");
}
}
else { System.out.println("Invalid user imput, please try again!"); }
}
}
There were a few problems with your code, most of them already pointed by other users. I'll only add that the way you wrote those if/else statements, it would never enter some of them.
I don't have much time right now but if you still have any doubts after seeing this answer leave a comment and I'll answer ASAP.
I see a couple of errors in the code that you have shared :
In the statement "System.out.prinln("Let's play Rock, Paper, Scissors!\n" + "Enter a move: \n" + "R = Rock, P = Paper, S = Scissors");"
, it should be System.out.println().You have a spelling-error (missing 't' in 'print')
You need to initialize variable 'personPlay' for the code to compile. It is required to initialize local variables as they do not assume a default value.
Missing closing bracket for statement :'computerInt = generator.nextInt('.
Fixing these, would let the code compile .
I would suggest using curly braces with each if, else if or else conditions, that would give the code a neat look. Also , there is a long chain of nested if-else conditions which is hard to read and debug(in case of any issue). Try to start with simple conditions and then build your logic in steps , avoiding these many if else conditions.
I'm currently working on an assignment for my Intro to Java Course. I've completed majority of the assignment: refactor a Rock, Paper, Scissor game I created in the past but using methods. When my code is executed; it prints a welcome message, prompts for user input and then prints the user's choice and the CPU's choice.
My question: How do i implement a while loop into my methods so that after the code is executed it will run a best 2/3 games?
To my understanding, I know that I must use a loop in each method. Where the input from the user will be different and the cpu will generate another random move.
*Note: I'm not asking for a direct solution but for something conceptual as to what would be a good approach to this problem.
Below is my code:
package rpsmethods;
import java.util.Scanner;
import java.util.Random;
public class RPSMethods {
public static void displayOpeningMessage() {
System.out.println("Welcome to RPS Game 2.0!");
}
public static int getUserMove() {
Scanner input = new Scanner(System.in);
System.out.print("Select scissors (0), rock (1), or scissors (2): ");
int choice = 0;
if (input.hasNextInt()) {
choice = input.nextInt();
switch (choice) {
case 0:
System.out.println("You chose scissor!");
break;
case 1:
System.out.println("You chose rock!");
break;
case 2:
System.out.println("You chose paper!");
break;
default:
System.out.println("Not a valid input!");
System.out.print("Select scissors (0), rock (1), or scissors (2): ");
choice = input.nextInt();
}
}
return choice;
}
public static int getCPUMove() {
Random rnd = new Random();
int CPUMove = rnd.nextInt(3);
switch (CPUMove) {
case 0:
System.out.println("CPU chose scissor!");
break;
case 1:
System.out.println("CPU chose rock!");
break;
case 2:
System.out.println("CPU chose paper!");
break;
}
return CPUMove;
}
public static void determineWinner(int user, int cpu) {
//User win scenarios
if (user == 0 && cpu == 2) {
System.out.println("You win, Scissors beat Paper!");
} else if (user == 1 && cpu == 0) {
System.out.println("You win, Rock beats Scissors!");
} else if (user == 2 && cpu == 1) {
System.out.println("You win, Paper beats Rock!");
}
//Cpu win scenarios
if (user == 0 && cpu == 1) {
System.out.println("You lose, Rock beats Scissors!");
} else if (user == 1 && cpu == 2) {
System.out.println("You lose, Paper beats Rock!");
} else if (user == 2 && cpu == 0) {
System.out.println("You lose, Scissor beats Paper!");
}
//Draw scenarios
if (user == 0 && cpu == 0) {
System.out.println("You and CPU chose Scissor, it's a draw!");
} else if (user == 1 && cpu == 1) {
System.out.println("You and CPU chose Rock, it's a draw!");
} else if (user == 2 && cpu == 2) {
System.out.println("You and CPU chose Paper, it's a draw!");
}
}
public static void main(String[] args) {
displayOpeningMessage();
int userWinner = getUserMove();
int CpuWinner = getCPUMove();
determineWinner(userWinner, CpuWinner);
}
}
You can define two static variables to check the final winner in your
class:
static int cpuScore = 0;
static int humanScore = 0;
Then, you can set a value for that variables inside determineWinner like this:
if (CPU wins)
cpuScore++
else
humanScore++;
Then you can put your top level steps inside a loop like this:
while (cpuScore < 2 && humanScore < 2) {
...
}
I am very new at coding and attempted to make a rock paper scissors code based on one I saw on here. However, when the system is supposed to output the result of the game after in prints what the computer played, it just does not print. Any ideas? Thanks!
import java.util.Scanner;
import java.util.Random;
public class Rock {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random gen = new Random();
System.out.println("Hey, let's play Rock, Paper, Scissors!\n" +
"Please enter a move.\n" + "Rock = R, Paper" +
"= P, and Scissors = S.");
int computerInt = gen.nextInt(3)+1;
String computerPlay = "";
if (computerInt == 1)
computerPlay = "R";
else if (computerInt == 2)
computerPlay = "P";
else if (computerInt == 3)
computerPlay = "P";
System.out.print("Please enter your play: ");
String personPlay = scan.next();
personPlay = personPlay.toUpperCase();
System.out.println("Computer play is: " + computerPlay);
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
else if (personPlay.equals("P"))
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
else if (personPlay.equals("S"))
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
else
System.out.println("Invalid user input.");
}
}
The nesting of your if statements is totally wrong. Your indentation (kind of almost) hints at how you wish your code be executed, but the compiler does not care at all about your indentation, it only obeys the rules of the java language.
Multiple nested conditional statements like if() else if() if() are notoriously hard to determine (by a human) how they will be executed.
So: never use more than one statement without curly braces. (Some even say to always use curly braces, even if you have only one statement.)
When there is even the slightest ambiguity, (as there is in the code you have written,) make sure to always add curly braces to ensure that the compiler will compile your code the way you intend it to.
Then, your code will (probably) work.
The two big things in coding are making your code both easy to read and functional. Those if statements do not fulfill either of those needs. Also you do not use curly braces... Use curly braces{}! This is your code but I have organised it to be a little more clean. Also I honestly don't know exactly why it didn't print in your original code, but that is not the problem. This one works.
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
private static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
String personPlay;
String computerPlay = "";
int computerInt;
Random gen = new Random();
System.out.println("Hey, let's play Rock, Paper, Scissors!\n" + "Please enter a move.\n" + "Rock = R, Paper"
+ "= P, and Scissors = S.");
computerInt = gen.nextInt(3) + 1;
if (computerInt == 1) {
computerPlay = "R";
}
if (computerInt == 2) {
computerPlay = "P";
}
if (computerInt == 3) {
computerPlay = "P";
}
System.out.print("Please enter your play: ");
personPlay = scan.next();
personPlay = personPlay.toUpperCase();
System.out.println("Computer play is: " + computerPlay);
if (personPlay.equals(computerPlay)) {
System.out.println("It's a tie!");
}
if (personPlay.equals("R") && computerPlay.equals("S")) {
System.out.println("Rock crushes scissors. You win!!");
}
if (personPlay.equals("R") && computerPlay.equals("P")) {
System.out.println("Paper eats rock. You lose!!");
}
if (personPlay.equals("P") && computerPlay.equals("R")) {
System.out.println("Paper eats rock. You win!!");
}
if (personPlay.equals("P") && computerPlay.equals("S")) {
System.out.println("Scissor cuts paper. You lose!!");
}
if (personPlay.equals("S") && computerPlay.equals("R")) {
System.out.println("Rock breaks scissors. You lose!!");
}
if (personPlay.equals("S") && computerPlay.equals("P")) {
System.out.println("Scissor cuts paper. You win!!");
}
if (!computerPlay.equals("R") && !computerPlay.equals("P") && !computerPlay.equals("S")) {
System.out.println("Invalid user input.");
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm new to programming and I'm trying to write a very simple Rock, Paper, Scissors game in Java. It will compile and run fine, but I am looking to say something like "Invalid move. Try again." or something along those lines for when the user (personPlay) does not enter a correct character (r, p, or s). What would be the best way to do so? For example, if you enter a "q", it should print "Invalid move." Thank you so much in advance!
// *************
// Rock.java
// *************
import java.util.Scanner;
import java.util.Random;
public class Rock
{
public static void main(String[] args)
{
String personPlay; //User's play -- "R", "P", or "S"
String computerPlay = ""; //Computer's play -- "R", "P", or "S"
int computerInt; //Randomly generated number used to determine
//computer's play
String response;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
System.out.println("Hey, let's play Rock, Paper, Scissors!\n" +
"Please enter a move.\n" + "Rock = R, Paper" +
"= P, and Scissors = S.");
System.out.println();
//Generate computer's play (0,1,2)
computerInt = generator.nextInt(3)+1;
//Translate computer's randomly generated play to
//string using if //statements
if (computerInt == 1)
computerPlay = "R";
else if (computerInt == 2)
computerPlay = "P";
else if (computerInt == 3)
computerPlay = "S";
//Get player's play from input-- note that this is
// stored as a string
System.out.println("Enter your play: ");
personPlay = scan.next();
//Make player's play uppercase for ease of comparison
personPlay = personPlay.toUpperCase();
//Print computer's play
System.out.println("Computer play is: " + computerPlay);
//See who won. Use nested ifs
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
else if (personPlay.equals("P"))
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
else if (personPlay.equals("S"))
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
else
System.out.println("Invalid user input.");
}
}
I would recommend making Rock, Paper and Scissors objects. The objects would have the logic of both translating to/from Strings and also "knowing" what beats what. The Java enum is perfect for this.
public enum Type{
ROCK, PAPER, SCISSOR;
public static Type parseType(String value){
//if /else logic here to return either ROCK, PAPER or SCISSOR
//if value is not either, you can return null
}
}
The parseType method can return null if the String is not a valid type. And you code can check if the value is null and if so, print "invalid try again" and loop back to re-read the Scanner.
Type person=null;
while(person==null){
System.out.println("Enter your play: ");
person= Type.parseType(scan.next());
if(person ==null){
System.out.println("invalid try again");
}
}
Furthermore, your type enum can determine what beats what by having each Type object know:
public enum Type{
//...
//each type will implement this method differently
public abstract boolean beats(Type other);
}
each type will implement this method differently to see what beats what:
ROCK{
#Override
public boolean beats(Type other){
return other == SCISSOR;
}
}
...
Then in your code
Type person, computer;
if (person.equals(computer))
System.out.println("It's a tie!");
}else if(person.beats(computer)){
System.out.println(person+ " beats " + computer + "You win!!");
}else{
System.out.println(computer + " beats " + person+ "You lose!!");
}
You could insert something like this:
personPlay = "B";
while (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S")) {
//Get player's play from input-- note that this is
// stored as a string
System.out.println("Enter your play: ");
personPlay = scan.next();
//Make player's play uppercase for ease of comparison
personPlay = personPlay.toUpperCase();
if (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S"))
System.out.println("Invalid move. Try again.");
}
Before we try to solve the invalid character problem, the lack of curly braces around the if and else if statements is wreaking havoc on your program's logic. Change it to this:
if (personPlay.equals(computerPlay)) {
System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
}
else if (personPlay.equals("S")) {
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
}
else
System.out.println("Invalid user input.");
Much clearer! It's now actually a piece of cake to catch the bad characters. You need to move the else statement to somewhere that will catch the errors before you attempt to process anything else. So change everything to:
if( /* insert your check for bad characters here */ ) {
System.out.println("Invalid user input.");
}
else if (personPlay.equals(computerPlay)) {
System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
}
else if (personPlay.equals("S")) {
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
}
Why not check for what the user entered and then ask the user to enter correct input again?
eg:
//Get player's play from input-- note that this is
// stored as a string
System.out.println("Enter your play: ");
response = scan.next();
if(response=="R"||response=="P"||response=="S"){
personPlay = response;
}else{
System.out.println("Invaild Input")
}
for the other modifications, please check my total code at pastebin
int w =0 , l =0, d=0, i=0;
Scanner sc = new Scanner(System.in);
// try tentimes
while (i<10) {
System.out.println("scissor(1) ,Rock(2),Paper(3) ");
int n = sc.nextInt();
int m =(int)(Math.random()*3+1);
if(n==m){
System.out.println("Com:"+m +"so>>> " + "draw");
d++;
}else if ((n-1)%3==(m%3)){
w++;
System.out.println("Com:"+m +"so>>> " +"win");
}
else if(n >=4 )
{
System.out.println("pleas enter correct number)");
}
else {
System.out.println("Com:"+m +"so>>> " +"lose");
l++;
}
i++;
I'm new to Java, and I created some sort of a mini game, and I wanted players to choose whether or not they want to play again, I tried changing my start boolean variable into static type and adding some lines of code, but the code doesn't seem to work, every time I play the game, it did ask me if I want to replay or not, but the problem is that even though I typed "yes" to the console at the end, the game doesn't seem to restart. Can anyone help me please, I would be really appreciated, thanks!
import java.util.Random;
import java.util.Scanner;
//Rocks, papers, scissors game complied by William To.
public class RockPaperScissor {
static int gamePlays = 0;
static boolean start = true;
public static void main(String[] args) {
while (start){
#SuppressWarnings("resource")
Scanner userInput = new Scanner(System.in);
Random comOutput = new Random();
System.out.println("Do you choose rock, paper or scissor?");
String userChoice = userInput.nextLine();
int comChoice = comOutput.nextInt(2);
switch (userChoice){
case "rock":
if(comChoice == 0){
System.out.println("I choose rock too! That's a draw!");
} else if(comChoice == 1){
System.out.println("I choose paper! I win!");
} else {
System.out.println("I choose scissor! You win!");
}
break;
case "paper":
if(comChoice == 0){
System.out.println("I choose rock! You win!");
} else if(comChoice == 1){
System.out.println("I choose paper too! That's a draw!");
} else {
System.out.println("I choose scissor! I win!");
}
break;
case "scissor":
if(comChoice == 0){
System.out.println("I choose rock! I win!");
} else if(comChoice == 1){
System.out.println("I choose paper! You win!");
} else {
System.out.println("I choose scissor too! That's a draw!");
}
break;
default :
System.out.println("I don't think that's an option.");
break;
}
gamePlays++;
System.out.println("You've played " + gamePlays + " games.");
//BELOW IS THE PART I want to ask, what's wrong?
System.out.println("Do you want to play again?");
String playAgain = userInput.next();
if (playAgain == "yes"){
System.out.println("Restarting game...");
start = true;
} else if (playAgain == "no") {
System.out.println("Quitting game.");
start = false;
}
}
}
}
The print out from Eclipse:
Do you choose rock, paper or scissor?
rock **//my input**
I choose paper! I win!
You've played 1 games.
Do you want to play again?
yes **//my input**
Do you choose rock, paper or scissor?
paper **//my input**
I choose paper too! That's a draw!
You've played 2 games.
Do you want to play again?
no **//my input**
Do you choose rock, paper or scissor?
Comparison between strings needs the String#equals instead of ==. So this:
if (playAgain == "yes"){
System.out.println("Restarting game...");
start = true;
} else if (playAgain == "no") {
System.out.println("Quitting game.");
start = false;
}
Has to become this:
if (playAgain.equals("yes")){
System.out.println("Restarting game...");
start = true;
} else if (playAgain.equals("no")) {
System.out.println("Quitting game.");
start = false;
}
In order to work properly.
However, I suggest to use String#equalsIgnoreCase, because with equals, the comparison is case-sensitive, so if user inputs i.e. Yes or yEs, playAgain.equals("yes") will return false
UPDATE
As Maroun Maroun says, it is better to use
"yes".equals(playAgain)
and
"no".equals(playAgain)
Because if playAgain is null it won't throw a NullPointerException
Try:
if ("yes".equals(playAgain)) {
System.out.println("Restarting game...");
start = true;
} else if ("no".equals(playAgain)) {
System.out.println("Quitting game.");
start = false;
}
String#equals() checks the character equality of string, == checks memory reference.
The problem is probably this line
if (playAgain == "yes")
(and the one later for no).
Strings in Java are objects. This means that two strings might have the same content, i.e. contain the same text, but still not be "the same" as far as == is concerned. To compare two strings and see if they contain the same text, use this:
if (playAgain.equals("yes"))
Problem is with the way in which String comparision is done.
playAgain == "yes", This check will check for object equality.
However in this case, value of object needs to be compared, following code will work for you.
playAgain.equals("yes")
You need compare string using String.equals() method and not ==
The equals method compares for the value of the string and == checks whether both the objects refer to the same same object or not.