如何拒绝 java 程序中的字符/字母

How to reject characters/ letters in a java program

当程序要求用户输入10个元素(数字),但用户输入任何字母或单词时,我希望程序显示“INVALID INPUT”。我尝试了一个 if 语句,但它不起作用。非常感谢任何帮助!

这是我的代码:

        int [] Array = new int[10];
        int index;

        Scanner input = new Scanner(System.in);

            System.out.println("Enter 10 elements:");

            for (int i = 0; i < 10; i++) {
                Array[i] = input.nextInt();
            }

        System.out.print("Enter an index you want to retrieve: ");
        index = input.nextInt();

        System.out.print("Element at index "+index+" is " + Array[index]);
    }
}

您可以使用 try-catch 并捕获 InputMismatchException,然后您可以在其中相应地处理它。

像这样:

    try{
       int [] Array = new int[10];
        int index;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter 10 elements:");
        for (int i = 0; i < 10; i++) {
            Array[i] = input.nextInt();
        }
        System.out.print("Enter an index you want to retrieve: ");
        index = input.nextInt();
        System.out.print("Element at index "+index+" is " + Array[index]);
    }catch(InputMismatchException e){
        System.out.println("INVALID INPUT");
    }

例如,当我输入:

spectric is not cool

我得到:

INVALID INPUT

因为光谱很酷

请尝试以下操作:您需要捕获输入不匹配,然后继续接受输入。重要的是更新循环计数器以允许获取所有 10 个输入。

int [] Array = new int[10];
int index;

Scanner input = new Scanner(System.in);

System.out.println("Enter 10 elements:");

     for (int i = 0; i < 10; i++) {
        try {
           Array[i] = input.nextInt();
        } catch(InputMismatchException ie) {
            System.out.println("Bad input - please re-enter");
            i--; // update loop;
            input.nextLine();// clear bad input from buffer scanner.
        }
     }

   System.out.print("Enter an index you want to retrieve: ");
   index = input.nextInt();

   System.out.print("Element at index "+index+" is " + Array[index]);