代码如下,我的目的是输入一个int,考虑到用户可能会输入错误,所以我在外面加了try catch,结果如果输入非int就发生了死循环一直输出错误,我想知道:
1.为什么会出现这个问题
2.如何解决类似的输入可能错误的问题?实际工作中也会try catch么package day03;import java.util.Scanner;public class ErrorDemo {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
while(true){
try {
int a = sc.nextInt();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// sc.nextLine();

}
}
}

}

解决方案 »

  1.   

    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while (true) {
    try {
    int a = sc.nextInt();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    // sc.nextLine();
    System.exit(1);
    }
    }
    }
      

  2.   


    import java.util.*;public class ScannerDemo {
        public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while(sc.hasNext()){
     try{
    int i = sc.nextInt();
    System.out.println(i);
     }catch(InputMismatchException e){
     System.out.println("请输入一个数字");
     sc.next();
     }
    }
    }
    }
      

  3.   

    你能告诉我的程序错在哪里了么。为什么会一直输出错误?按说我try catch 一次下次输入正确就可以了把?
      

  4.   

    int i = sc.nextInt();
    被不断的验证,所以不断的报错
      

  5.   

    兄弟你看清我的问题。为什么会一直输出错误?我try catch 掉,理当第二次的时候还会让我重新输入的。但是它会一直报错下去。
      

  6.   

    兄弟,能告诉我,我第一次try catch了,按说第二次就可以正常输入int 值了。它为什么就不断验证了呢?谢谢。
      

  7.   

    一旦产生异常,sc就不会继续监听下去,只会停在出错的地方,也就是说int i = sc.nextInt();这个地方,所以每次循环都会产生异常,sc不往下走,用户就即便输入正确数字也没有用,而只会停留在上次输入错误的地方不断验证,下面给上我的代码,做的不好,但基本上也能符合楼主的要求吧。
    import java.util.Scanner;public class ErrorDemo
    {
    public static void main(String[] args)
    {
    m();
    } public static void m()
    {
    System.out.println("请输入:");
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext())
    {
    try
    {
    int a = sc.nextInt();
    System.out.println(a);
    }
    catch (Exception e)
    { System.out.println("输入不合法");
    m();
    }
    }
    }
    }