每当我运行此代码时,如果我键入一个字符串作为我的输入,我会在第 11 行出现错误。帮助?我不确定如何运行 else 语句或询问如果他们放置字符串而不是整数(选择变量)会怎样的东西。我是新来的,非常感谢!
这是我的代码:
import java.util.Scanner;
public class rockPaper {
public static void main(String args[]) {
System.out.println("Hello world");
int rock = 0;
int paper = 1;
int scissors = 2;
Scanner input = new Scanner(System.in);
System.out.println("Rock, Paper, or Scissors(0, 1, or 2)? Enter your integer: ");
int choice = input.nextInt();
int aIChoice = (int) (Math.random() * 3);
if (choice == rock) {
switch (aIChoice) {
case 0:
System.out.println("AI chose rock.");
System.out.println("Rock ties with rock!");
break;
case 1:
System.out.println("AI chose paper.");
System.out.println("Fail. Paper trumps rock.");
break;
case 2:
System.out.println("AI chose scissors.");
System.out.println("You win! Rock trumps scissors.");
break;
default:
break;
}
} else if (choice == paper) {
switch (aIChoice) {
case 0:
System.out.println("AI chose rock.");
System.out.println("You win! Paper trumps rock.");
break;
case 1:
System.out.println("AI chose paper.");
System.out.println("Paper ties with paper!");
break;
case 2:
System.out.println("AI chose scissors.");
System.out.println("Fail. Scissors trumps paper.");
break;
default:
break;
}
} else if (choice == scissors) {
switch (aIChoice) {
case 0:
System.out.println("AI chose rock.");
System.out.println("Fail. Rock trumps scissors.");
break;
case 1:
System.out.println("AI chose paper.");
System.out.println("You win! Scissors trumps paper.");
break;
case 2:
System.out.println("AI chose scissors.");
System.out.println("Scissors ties with scissors!");
break;
default:
break;
}
} else {
System.out.println("Nope!");
}
input.close();
}
}
如上所述,如果我运行代码,并输入任何字母(字符串),则引用第 11 行时会出现错误。我不确定我应该怎么做,因为显然正如我提到的,在所有这些中添加一个 else 语句并不能确保如果他们输入字符串时"nope"。
通常您不会接受字符串输入。 如果您出于某种原因确实需要,您可以将输入行替换为String choice = input.next()
然后对其进行任何您需要的测试。 确认它是您想要的输入后,请参阅这篇文章以从字符串转换为 int。
不太确定如果用户提供无效的输入,您会期望什么,但是,我认为,合理的选择是检查输入并在输入不是有效整数时向用户打印错误消息。为此,只需在下面添加此代码,而不是代码中的此行:int choice = input.nextInt();
int choice = -1;
if (input.hasNextInt()) {
choice = input.nextInt();
} else {
System.out.println("Please provide valid integer input: Rock, Paper, or Scissors(0, 1, or 2)?");
}
附言此外,最好检查您的整数是否在 [0,2] 范围内。