当程序要求用户输入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
因为光谱很酷
关于java - 如何在java程序中拒绝字符/字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64056136/