如何在java中处理用户输入类型?
如果我的程序中允许的输入仅为如何在java中处理用户输入类型?,java,Java,如果我的程序中允许的输入仅为int类型,但它们使用户可以任意键入不允许的类型字符,例如double或char等。我如何处理?我肯定会有这样的抛出异常之类的事情,但我只是不确定它是如何做到的。如有任何建议,将不胜感激 //here is my code System.out.print("Too " +additionalInfo+ "! Try again: "); attemptCounter++; int x= input.nextInt(); // here is where i want
int
类型,但它们使用户可以任意键入不允许的类型字符,例如double
或char
等。我如何处理?我肯定会有这样的抛出异常之类的事情,但我只是不确定它是如何做到的。如有任何建议,将不胜感激
//here is my code
System.out.print("Too " +additionalInfo+ "! Try again: ");
attemptCounter++;
int x= input.nextInt(); // here is where i want the usr to type in their input
使用循环在无效输入后再次提示用户输入,例如
int userInput;
while(true) {
try {
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
userInput = input.nextInt();
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
System.out.println("Invalid Number, Please try again");
}
}
声明:Throws:InputMismatchException-如果下一个标记与整数正则表达式不匹配,或超出范围。通过阅读你的课本来学习异常,或者如果你因为我链接了异常教程而如此爱我,那么你应该学会爱谷歌。通常,在Google中键入“java教程”会直接导致上的java教程。键入“SomeClass java api doc”直接导致SomeClass的javadoc。或者您可以将javadoc主页添加书签,并浏览包和类。学会自主。