当我运行它时,它会显示案例中的所有System.out.println("")
语句。如何让它选择正确的if
语句而不是其他内容?
如果我能在找到结果后回到起点,这也会有所帮助。
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;
}
}
}
}
答案 0 :(得分:5)
你有两个问题:
1)你的if语句没有运行,因为它们以分号结尾。这意味着{}中的代码形成一个块并以任何一种方式运行。
2)你的休息是在错误的地方。如果选择'R'(或'r'),第一个只会中断。如果案件运行则后者会中断。
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;
另外,正如评论中所建议的那样,您可以使用循环来提示输入。例如:
while (! done) {
System.out.print("Rock(R) Paper(P) or Scissors(S)? (or Quit(Q) ");
reply = myScanner.findWithinHorizon(".", 0).charAt(0);
// more code here
}
这里你需要另一个案例,所以你可以将done设置为true并结束循环。
答案 1 :(得分:4)
您使用额外的;
if语句的语法是:
if(condition){
Expressions;
}
分号是这样的:
if(condition)
; //empty line, effectively ignores the if
{
Expressions;
}