在while循环中处理捕获输入的异常当出现异常并捕获之后就出现了问题这是我的代码:
......while(true){
try{
System.out.println("请输入学号:");
n=scan.nextInt();
break;
}catch(Exception e){
System.out.println("请输入整数!");
}
}
......当输入一个不是整数的时候它就会出现下面的死循环:请输入整数!
请输入学号:
请输入整数!
请输入学号:
请输入整数!
请输入学号:
请输入整数!
请输入学号:
......
在"请输入整数!"和请输入学号"之间没有停顿!!!请问大家这该怎么解决?有没有其他方法可以代替?
......while(true){
try{
System.out.println("请输入学号:");
n=scan.nextInt();
break;
}catch(Exception e){
System.out.println("请输入整数!");
}
}
......当输入一个不是整数的时候它就会出现下面的死循环:请输入整数!
请输入学号:
请输入整数!
请输入学号:
请输入整数!
请输入学号:
请输入整数!
请输入学号:
......
在"请输入整数!"和请输入学号"之间没有停顿!!!请问大家这该怎么解决?有没有其他方法可以代替?
while(flag){try{
System.out.println("请输入学号:");
n=scan.nextInt();
break;
}catch(Exception e){
System.out.println("请输入整数!");
flag = false;
}
}
n=scan.nextInt();
break;
}
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
然后再进入循环,打印:请输入学号:。可是它没有等待你输入又直接捕获异常是因为Scanner方法中会留下缓存,JVM直接把上一次的缓存提取为你这次的输入结果。所以依旧报错……
try {
System.out.println("请输入学号:");
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
break;
} catch (Exception e) {
System.out.println("请输入整数!");
}
}红色的这一句需要放到while循环里
public class TryUse { /**
* @param args
*/
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=0;
while(true){
try{
scan=new Scanner(System.in);//重新简历Scanner就行了
System.out.println("请输入学号:");
n=scan.nextInt();
break;
}catch(Exception e){
System.out.println("请输入整数!");
//n=scan.nextInt(); }
} }}
try {
Scanner scan = new Scanner(System.in);
System.out.println("请输入学号:");
n = scan.nextInt();
break;
} catch (Exception e) {
System.out.println("请输入整数!\n");
}
}
用这段代码可以达到你的需求