日期:2014-05-20  浏览次数:20696 次

我输入字符串怎么出现无限循环了啊??求解
public static void main(String[] args) {
int n = 0,m = 0;
Scanner in=new Scanner(System.in);
while(true) {
try{
System.out.println("请输入numsOfSlave:");
n = in.nextInt();
System.out.println("请输入removeM:");
m = in.nextInt();
josephus(n,m);
break;
}catch(Exception e){
e.printStackTrace();
}
}

}
我输入一个字符串
结果是:请输入numsOfSlave:
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Josephus.main(Josephus.java:11)
请输入numsOfSlave:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Josephus.main(Josephus.java:11)
请输入numsOfSlave:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Josephus.main(Josephus.java:11)
请输入numsOfSlave:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Josephus.main(Josephus.java:11)
请输入numsOfSlave:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Josephus.main(Josephus.java:11)
请输入numsOfSlave:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Josephus.main(Josephus.java:11)
请输入numsOfSlave:
无限循环;

------解决方案--------------------
起始原因是你输入了一个非int型的字符串,所以获得一个异常,然后就开始打印异常,然后就重复的去捕获异常,由于也是控制台刷出的,所以就一直去nextInt,一直就这样死循环了
------解决方案--------------------
你输入的类型发生错误了!处理完之后,这个值又继续识别,然后还是错误!

所以,当类型发生错误的时候,你把错误的信息当字符串读出来,让他读下一个就好了!