如果他们将字符串放在 int 输入变量上,如何添加 else 语句?

每当我运行此代码时,如果我输入一个字符串作为输入,我会在第 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 语句并不能确保如果他们输入了一个字符串则“不”。


大话西游666
浏览 145回答 2
2回答

陪伴而非守候

通常你不会接受字符串输入。如果您出于某种原因确实需要,您可以将输入行替换为String choice = input.next()then 进行任何您需要的测试。在您确认它是您想要的输入后,请参阅这篇文章以从 String 转换为 int。

牧羊人nacy

不太确定如果用户提供无效输入,您期望什么,但我认为,如果输入不是有效整数,合理的选择是检查输入并向用户打印错误消息。为此,只需在下面添加此代码,而不是在代码中添加此行: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] 范围内。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java