String input doesn't work in if-else statement - java

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.

Related

Looping a 2 player rock paper scissors game (Java)

im trying to create a 2 player rock paper scissors game with a prompt to continue or end the game. and also re-ask for your move if entered incorrectly. i've been trying to use do-while loops but i get an error every time.
it doesn't recognize the do-while i put in, because it's not reading the while(playAgain.equals("Y");
let me know what i can fix and where i should start my do and start my while. thanks!
import java.util.Scanner;
public class RPS {
public static void main(String[] args) {
//player one input
Scanner in = new Scanner(System.in);
//loop start?
do {
System.out.println("Player One, please enter your move [R/P/S]: ");
String playerOne = in.nextLine();
//verify move is valid
if (!playerOne.equals("R") && !playerOne.equals("P") && !playerOne.equals("S")) {
System.out.println("Invalid input, please enter valid move.");
} else {
//player two input
System.out.println("Player Two, please enter your move [R/P/S]: ");
String playerTwo = in.nextLine();
//verify move is valid
if (!playerTwo.equals("R") && !playerTwo.equals("P") && !playerTwo.equals("S")) {
System.out.println("Invalid input, please enter valid move.");
}
//game outcome
if (playerOne.equals(playerTwo)) {
System.out.println("You tied!");
} else if (
(playerOne.equals("R") && playerTwo.equals("S")) ||
(playerOne.equals("S") && playerTwo.equals("P")) ||
(playerOne.equals("P") && playerTwo.equals("R"))) {
System.out.println("Player One has won!");
} else if (
(playerTwo.equals("R") && playerOne.equals("S")) ||
(playerTwo.equals("S") && playerOne.equals("P")) ||
(playerTwo.equals("P") && playerOne.equals("R"))) {
System.out.println("Player Two has won!");
}}}//loop end?
while (playAgain.equals("Y"));
//prompt user to play again
System.out.println("Would you like to play again? [Y/N]");
String playAgain = in.nextLine();
if (playAgain.equals("N")) {
System.out.println("Game stopped. Thanks for playing!");
}
if (!playAgain.equals("Y") && !playAgain.equals("N")) {
System.out.println("Invalid input, please enter valid response.");
}}}
I will look further, though to improve readability|simplify logic
if (!playerOne.equals("R") && !playerOne.equals("P") && !playerOne.equals("S"))
is the same as
if (!((playerOne.equals("R") || playerOne.equals("P") || playerOne.equals("S")))
EDIT: In your logic, I don't see a case for asking the player again. This can/will lead to a logic hole.
bool inPlay = true;
while(inPlay)
{
...
if(valid plays)
{
if(tie) print tie;
else if(p1 wins) print player1;
else if(p2 wins) print player2;
inPlay = ask: want to play again?
}else
{
tell them it is invalid, loop again;
}
...
}
^This will allow you to ask again
EDIT 2: for a do-while, it is essentially the same deal:
bool inPlay = true;
do
{
above logic;
}while(inPlay);
EDIT 3: With your most recent version I see a vital flaw here:
do
{
...
}
while (playAgain.equals("Y"));//<-- semicolon
//prompt user to play again
System.out.println("Would you like to play again? [Y/N]");
...
You can't go back to the start of the do-while loop with that prompt after the semicolon ; has been reached. You need to ask that question within the curly brackets {} after the game has been finished.
EDIT 4: to expand on OP's "I'm getting an error that my playAgain variable is not initialized even when I add String playAgain;"
String playAgain = "";
do
{
...
playAgain = their answer;
...
}while(playAgain.equals("Y"));
However, I don't think you need to keep the String outside the scope of the loop, a boolean is all you need, and a boolean is easier to read. So perhaps:
//See EDIT 2 above
...
// will result in true for Y and false for !Y
playAgain = (answer == 'Y')
...

I can't figure out how to restart a loop, when the person enters in a wrong input

Ok so for an assignment I need to make a loop for the user to input a number 1-4 for either rock paper scissors or to end the game, but if they enter in anything other than those I need them to be able to re-enter the number but I can't seem to get my loop to restart or something similar...
Code (It's just my while loop
while(user < 5)
{
System.out.println("Please enter in a number");
computer = generator.nextInt(3) + 1;
user = keyboardIn.nextInt();
//tell the player what was chosen
if(user == 1)//player is rock
{
System.out.println ("Player is rock");
}
else if (user == 2)//player is paper
{
System.out.println ("Player is paper");
}
else if (user == 3) //player is scissors
{
System.out.println ("Player is scissors");
}
else if (user == 4)
{
System.out.println("Thank you for playing!");
break;
}
else if (user >= 5)
{
System.out.println(user + " was never an option. \nTry again.");
user = keyboardIn.nextInt();
}
//tell the player what the computer has chosen
if(computer == 1)//computer is rock
{
System.out.println ("Computer is rock");
}
else if (computer == 2)//computer is paper
{
System.out.println ("Computer is paper");
}
else if (computer == 3)//computer is scissors
{
System.out.println ("Computer is scissors");
}
//determine winner
if (user == computer) //tie
{
System.out.println("It is a tie");
}
else if (user < computer) //player is rock
{
System.out.println("Computer wins");
}
else //computer is scissors
{
System.out.println("Player wins");
}
System.out.println();
}
You can use continue to jump back to the top of the loop. Note, however, that at the top you ask for user input, and on error you do so too; that's one time too many.
You could use
boolean gameOver = false;
while(!gameOver){
if (user < 5){
....
}
}
and set gameOver = true in each of your game-ending conditions.
Replace the part:
else if (user >= 5)
{
System.out.println(user + " was never an option. \nTry again.");
user = keyboardIn.nextInt();
}
With:
else if (user >= 5)
{
System.out.println(user + " was never an option. \nTry again.");
continue;
}
Basically the continue, brakes the current loop and start over a new one, of course verifying first the condition...
However if you want your code to be a little bit more efficient, in your specific case this would be my way of doing it:
while(true) {
computer = generator.nextInt(3) + 1;
do {
System.out.println("Please enter in a number");
user = keyboardIn.nextInt();
} while(user>=5 && user<=0);
//The rest of your code deleting also the last else if statement
}
This way your code is cleaner and more maintainable. Plus you will be sure that after the code exit from the loop you will definitely have a number between 0 and 4 which would be a valid option

Is there a way of condensing this method of comparing multiple outcomes?

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 :)

Need to get the entire thing in a loop, which loop is best suited? Where should I apply it?

I am nearly finished with a Java project of mine. The objective is to play a game of Rock Paper Scissors with the user and the computer. The computer generates a random number and that number must correlate with either one of the three choices. I got it to where it can play successfully, but here is the catch, in the case of a tie, the game is to repeat and start over, otherwise it is to terminate. I have it to where it terminates, but cannot figure out how to get it to repeat the entire process in the case of a tie. The methods must remain the way they are, but my professor said the answer is if the entire thing is in a loop. My question is which loop should I use and where should it be placed? Here is the code:
public class FahrDylanRockPaperScissors{
public static void main (String [] args){
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 String userChoice(){
Scanner sc = new Scanner (System.in);
String user = "default";
do{
System.out.println ("Let's Play a game! Rock, Paper, Scissors!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! " + "\nPlease enter either Rock, Paper, or Scissors: " + "\nGood Luck!");
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 void 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.");
}
}
You can use a do-while loop, because your code needs to be executed at least one time.
public static void main (String [] args){
boolean win = false;
do{
String computer = computerChoice();
String user = userChoice();
win = determineWinner(computer, user);
}while(!win);
}
For the first time you execute the whole code. Then the predicate is checked, and if someone won, the do-while will stop. But if win equals false it will be executed again.
You could achieve the same with only a while loop, or other loops. But because your code needs to be run at least one time a do-while suits well.
Edit:
You need to change your code, so that determineWinner returns back if someone won (return true) or if there is a tie (return false). I did not see that it currently has no return type when posting the answer.
A simple way to get the determineWinner method to work would be the following.
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;
}
And for your coding style:
It's good practice to use brackets {} for if/else/for... even if you have only one statement, because it improves the readability of your code.
Edit 2:
Because you can't change something, the easiest way is probably the following:
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);
}
Even if determineWinner determines the winner you need it to give you feedback. If you can't get feedback, just determine if there will be a tie in your main-Method, and if you get a tie, repeat.
You could easily just make the three lines:
public static void playGame()
{
String computer = computerChoice();
String user = userChoice();
determineWinner(computer, user);
}
into one new method, something like playGame(). Then in the main function, you can call playGame(), and at the end of determineWinner(), you could have:
else if (computer.compareTo(user) == 0 )
{
System.out.println(" Tie! the game must be played again.");
playGame();
}
to play the game again.
Also, make sure you include the import statements for Random and Scanner. And make sure you close your scanner.
Use a flag for tie, something like this:
boolean tie = false;
combine with do while:
do {
} while (tie);
if tie == true than keep going until its false.
A do { ... } while () loop would be most natural for this problem, but pretty much any loop construct could serve.
Although you say
The methods must remain the way they are
you cannot do it if the determineWinner() method remains exactly as it now is. That method needs one way or another to communicate back to main() whether there is a tie, or else it must itself manage running a new game in the event of a tie. Were I free to do so, I would have it return a a boolean value indicating whether there was a tie. If it cannot be modified to return a value, then the other alternative would be for it to set a static variable to indicate whether there was a tie. Alternatively, you could solve this problem with recursion, but that would not involve a loop.

Rock, Paper, Scissors Game Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 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++;

Categories

Resources