如何在java程序中拒绝字符/字母
当程序要求用户输入10个元素(数字),但用户输入了任何字母或单词时,我希望程序显示“无效输入”。我尝试了一个if语句,但它不起作用。非常感谢您的帮助 这是我的代码:如何在java程序中拒绝字符/字母,java,printf,invalid-characters,Java,Printf,Invalid Characters,当程序要求用户输入10个元素(数字),但用户输入了任何字母或单词时,我希望程序显示“无效输入”。我尝试了一个if语句,但它不起作用。非常感谢您的帮助 这是我的代码: int [] Array = new int[10]; int index; Scanner input = new Scanner(System.in); System.out.println("Enter 10 elements:"
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]);
}
}
int[]数组=新的int[10];
整数指数;
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入10个元素:”);
对于(int i=0;i<10;i++){
数组[i]=input.nextInt();
}
System.out.print(“输入要检索的索引:”);
index=input.nextInt();
系统输出打印(“索引处的元素”+索引+”是“+数组[index]);
}
}
您可以使用一个try catch
并捕获一个输入不匹配异常
,然后您可以相应地处理它
像这样:
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");
}
我得到:
INVALID INPUT
因为spectric很酷请尝试以下方法:您需要捕获输入不匹配,然后继续输入。重要的是更新循环计数器,以允许采用所有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]);
int[]数组=新的int[10];
整数指数;
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入10个元素:”);
对于(int i=0;i<10;i++){
试一试{
数组[i]=input.nextInt();
}捕获(输入不匹配异常ie){
System.out.println(“输入错误-请重新输入”);
i--;//更新循环;
input.nextLine();//清除缓冲区扫描程序中的错误输入。
}
}
System.out.print(“输入要检索的索引:”);
index=input.nextInt();
系统输出打印(“索引处的元素”+索引+”是“+数组[index]);
显然有人不喜欢我们的答案。@WJS这些答案对我来说非常好。不知道为什么。
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]);