问题描述
当程序要求用户输入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]);