2 回答
TA贡献1900条经验 获得超5个赞
为了真正处理无效输入,您需要在循环中首先完成此操作。此外,你不能在你的语句块中这样做,因为在那些你检查的语句中,而不是输入,所以它没有意义,它永远不会起作用。此外,您将输入检查为从中获取的内容,但是例如,如果用户插入一个字符串,例如您只查看第一个字母,然后将其作为有效输入。我修改了你的代码,以便你在每次循环迭代中读取一行,如果这一行不是,它将被视为无效输入,如果它的程序将完成。else
if-else
if-else
randomNumber
sc.next().charAt(0)
"R_invalid_something_without_space"
R
q / r / p / s
q
public static void main(String[] args) {
char userChar = 0;
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
// Intro/directions/prompting for user input
System.out.println("Welcome to Rock, Paper, Scissors by Rancid!");
System.out.println("Choose R for Rock, P for Paper, S for Scissors, or Q to Quit, then press Enter: ");
// Start of loop
while (true) {
// what I changed
// **********************************************************
String line = sc.nextLine().toLowerCase();
if(line.equals("q")){
System.out.println("Player chose to quit. Goodbye!");
break;
}
if(!line.equals("r") && !line.equals("s") && !line.equals("p")) {
System.out.println("Invalid input! Please enter a valid character.");
continue;
}
userChar = line.charAt(0);
// **********************************************************
// Prompting computer to generate a random number
int randomNumber = rnd.nextInt(3) + 1;
// If computer generates 1 (Rock)
if (randomNumber == 1) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Rock vs. Rock! It's a tie!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Paper covers Rock, you win!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Rock breaks Scissors, you lose!");
}
}
// If computer generates 2 (Paper)
else if (randomNumber == 2) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Paper covers Rock, you lose!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Paper vs. Paper! It's a tie!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Scissors cuts Paper, you win!");
}
}
// If computer generates 3 (Scissors)
else if (randomNumber == 3) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Rock breaks Scissors, you win!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Scissors cuts Paper, you lose!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Scissors vs. Scissors! It's a tie!");
}
}
}
}
TA贡献1818条经验 获得超8个赞
好吧,首先,您退出的条件超出了 while 循环的范围,这意味着它永远不会在此给定上下文中执行。
其次,while 循环中的条件将不为 true,除非 userChar 不是同时是 q 和 Q,这是没有意义的。
我的建议是稍微重构一下你的 while 循环,如下所示:
while (true) {
//Your logic here
if (userChar == 'q' || userChar == 'Q') {
System.out.println("Player chose to quit. Goodbye!");
break;
}
//Your logic here
}
添加回答
举报