Java 如何循环用户输入直到输入整数?
我是Java新手,我想一直请求用户输入,直到用户输入一个整数,这样就不会出现InputMismatchException。我已经尝试过这段代码,但当我输入一个非整数值时仍然会出现异常Java 如何循环用户输入直到输入整数?,java,input,exception-handling,Java,Input,Exception Handling,我是Java新手,我想一直请求用户输入,直到用户输入一个整数,这样就不会出现InputMismatchException。我已经尝试过这段代码,但当我输入一个非整数值时仍然会出现异常 int getInt(String prompt){ System.out.print(prompt); Scanner sc = new Scanner(System.in); while(!sc.hasNextInt()){ System.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
谢谢你的时间 使用
next
而不是nextInt
进行输入。放置一个try-catch以使用parseInt方法解析输入。如果解析成功,请中断while循环,否则继续。
试试这个:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
或者,如果它只是一个单位数整数[0-9],则可以检查其ASCII码。它应该在48-57之间才能成为整数 基于Juned的代码,您可以使用if条件替换try块:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
System.out.println("Correct input, exit");
break;
}
System.out.println("Input is not a number, continue");
}
系统输出打印(“输入”);
扫描仪sc=新的扫描仪(System.in);
while(true){
System.out.println(“输入一个整数”);
字符串输入=sc.next();
int intInputValue=0;
如果(input.charAt(0)>=48&&input.charAt(0)较短的解,只需在sc.next()中输入
在处理朱纳德的代码时,我能够把它缩短
int getInt(String prompt) {
System.out.print(prompt);
while(true){
try {
return Integer.parseInt(new Scanner(System.in).next());
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n"+prompt);
}
}
}
在您仍有输入的情况下继续轻轻扫描,并根据需要检查它是否确实是整数:
String s = "This is not yet number 10";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
while (scanner.hasNext()) {
// if the next is a Int,
// print found and the Int
if (scanner.hasNextInt()) {
System.out.println("Found Int value :"
+ scanner.nextInt());
}
// if no Int is found,
// print "Not Found:" and the token
else {
System.out.println("Not found Int value :"
+ scanner.next());
}
}
scanner.close();
@Shail可能有更好的解决方案,但这是我可以用有限的能力创建的解决方案。如果有帮助,请接受答案。谢谢!
String s = "This is not yet number 10";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
while (scanner.hasNext()) {
// if the next is a Int,
// print found and the Int
if (scanner.hasNextInt()) {
System.out.println("Found Int value :"
+ scanner.nextInt());
}
// if no Int is found,
// print "Not Found:" and the token
else {
System.out.println("Not found Int value :"
+ scanner.next());
}
}
scanner.close();