如何在Java程序中拒绝字符/字母

问题描述

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

enter image description here

这是我的代码

        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]);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...