[英]How to add else statement if they put a string on an int input variable?
每当我运行此代码时,如果我输入字符串作为输入,我在第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()
然后对其进行任何测试。 确认为输入后,您要参考此文章以将String转换为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)?");
}
PS另外,最好检查您的整数是否在[0,2]范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.