每当我运行此代码时,如果我输入一个字符串作为输入,我会在第 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 { System.out.println("Nope!"); } input.close(); }}如上所述,如果我运行代码并输入任何字母(字符串),则会收到引用第 11 行的错误。我不确定我应该做什么,因为显然正如我提到的那样,在所有这些中添加一个 else 语句并不能确保如果他们输入了一个字符串则“不”。
2 回答
牧羊人nacy
TA贡献1862条经验 获得超7个赞
不太确定如果用户提供无效输入,您期望什么,但我认为,如果输入不是有效整数,合理的选择是检查输入并向用户打印错误消息。为此,只需在下面添加此代码,而不是在代码中添加此行: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] 范围内。
添加回答
举报
0/150
提交
取消
