Java program with embedded if else statements, not always printing what the code tells the program to print?

Question by Ashley: Java program with embedded if else statements, not always printing what the code tells the program to print?
My program is supposed to do the game rock paper scissors, when the player picks on and the computer randomly picks one. But when i run this program, and the user enters an R, r, S, or s, it does not print out the line i want it to, unless it is a tie, but when i enter R, or r the program prints what i want it to
What is wrong with my code that is causing this problem i have?
The following is the majority of my program:
computerInt = generator.nextInt(3);

//Translate computer’s randomly generated play to string
switch (computerInt)
{
case 0:
computerPlay = “R”;
break;
case 1:
computerPlay = “P”;
break;
default:
computerPlay = “S”;
}
//Gets the player’s play from input
System.out.println (“Enter your play: R, P, or S”);
personPlay = scan.next();

//Makes the player’s play uppercase for ease of comparison
personPlay = personPlay.toUpperCase();

//Prints computer’s play
System.out.println (“Computer play is ” + computerPlay);

//Compares the player’s input to the computer’s input and then
//prints out a statement announcing if the player won or lost
//and why.
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(“R”))
if (computerPlay.equals(“P”))
System.out.println(“Paper covers rock. You loose.”);
else if (personPlay.equals(“P”))
if (computerPlay.equals(“R”))
System.out.println(“Paper covers rock. You win!!”);
else if (personPlay.equals(“P”))
if (computerPlay.equals(“S”))
System.out.println(“Scissors cut paper. You loose.”);
else if (personPlay.equals(“S”))
if(computerPlay.equals(“P”))
System.out.println(“Scissors cut paper. You win!!”);
else if (personPlay.equals(“S”))
if (computerPlay.equals(“R”))
System.out.println(“Rock crushes scissors. You loose.”);
}
}

Best answer:

Answer by Mercuri
Wow, your if statements are a nested jumble of unreadable garbage. I recommend you use brackets and indentation to help separate them because right now you’re probably wanting to group the if/else statements differently than the compiler is reading them as.

Note: I know the formatting got messed up when you copied your code here, so the tabs/spacing was just for your personal use.

Add your own answer in the comments!

Leave a Reply

Your email address will not be published. Required fields are marked *


*