Reputation: 21
When I run this, it displays all System.out.println("")
statements in the case. How do I make it choose the correct if
statement and nothing else?
And if I could go back to the beginning after it finds an outcome, that would also be helpful.
import java.util.Scanner;
import java.util.Random;
public class TEST {
private static Scanner myScanner;
public static void main(String[] args) {
myScanner = new Scanner(System.in);
Random myRandom = new Random();
int randomNumber;
char reply;
System.out.print("Rock(R) Paper(P) or Scissors(S)? ");
reply = myScanner.findWithinHorizon(".", 0).charAt(0);
randomNumber = myRandom.nextInt(3) + 1;
switch (randomNumber) {
case 1:
if (reply == 'S' || reply == 's'); {
System.out.println("Computer: Rock. You lost!");
}
if (reply == 'R' || reply == 'r'); {
System.out.println("Computer: Rock. You tied!");
}
if (reply == 'P' || reply == 'p'); {
System.out.println("Computer: Rock. You won!");
break;
}
case 2:
if (reply == 'P' || reply == 'p'); {
System.out.println("Computer: Paper. You tied!");
}
if (reply == 'S' || reply == 's'); {
System.out.println("Computer: Paper. You won!");
}
if (reply == 'R' || reply == 'r'); {
System.out.println("Computer: Paper. You lost!");
break;
}
case 3:
if (reply == 'R' || reply == 'r'); {
System.out.println("Computer: Scissor. You won!");
}
if (reply == 'P' || reply == 'p'); {
System.out.println("Computer: Scissor. You lost!");
}
if (reply == 'S' || reply == 's'); {
System.out.println("Computer: Scissor. You tied!");
break;
}
}
}
}
Upvotes: 1
Views: 101
Reputation: 12266
You have two problems:
1) Your if statements don't run because they end in semi-colon. This means the code in {} forms a block and runs either way.
2) Your breaks are in the wrong place. The first only breaks if 'R' (or 'r') is chosen. The later breaks if the case is run.
if (reply == 'P' || reply == 'p'); {
System.out.println("Computer: Paper. You tied!");
}
if (reply == 'S' || reply == 's'); {
System.out.println("Computer: Paper. You won!");
}
if (reply == 'R' || reply == 'r'); {
System.out.println("Computer: Paper. You lost!");
break;
}
vs
if (reply == 'P' || reply == 'p') {
System.out.println("Computer: Paper. You tied!");
}
if (reply == 'S' || reply == 's') {
System.out.println("Computer: Paper. You won!");
}
if (reply == 'R' || reply == 'r') {
System.out.println("Computer: Paper. You lost!");
}
break;
Also, as suggested in the comments, you can use a loop to prompt for input. For example:
while (! done) {
System.out.print("Rock(R) Paper(P) or Scissors(S)? (or Quit(Q) ");
reply = myScanner.findWithinHorizon(".", 0).charAt(0);
// more code here
}
You'll need another case here so you can set done to true and end the loop.
Upvotes: 5
Reputation: 3650
You followed the if's with an extra ;
The syntax for an if statements is:
if(condition){
Expressions;
}
the semicolon makes it:
if(condition)
; //empty line, effectively ignores the if
{
Expressions;
}
Upvotes: 4