Java中的While嵌套try catch抛出意外循环输入验证使用方法

从控制台输入一个整数,如果输入的不是整数就通过catch捕获提示,并且循环重新输入,直到输入的内容是整数,然后打印输出的数

瓶颈点:
如果不重置Scanner对象sc将会总在while死循环 try catch,原因是Scanner对象发生异常后就不能再被使用,所以一直报异常,编程了死循环.如:
public static void main(String[] args) {
          Scanner sc = new Scanner(System.in);
          int num = 0;
          while (true) {
                   try {                             
                            System.out.println("请输入整数..");
                            num = sc.nextInt();
                            break;
                   } catch (InputMismatchException e) {
                                      System.out.println("输入数据有误");
                                      System.out.println("请重新输入..");
                                      }
                                     
                            }
              System.out.println("刚才输入的整数是:"+num);
         }
 
解决方法,只要每次重新new一个Scanner就可以了,但不推荐这么写,因为非常消耗性能,且异常的开资会非常的大,这里只是说明问题所在:
一:Scanner在while循环外的时候

public static void main(String[] args) {

                  Scanner sc = new Scanner(System.in);

                   int num = 0;

                   while (true) {

                            try {                             

                                     System.out.println("请输入整数..");

                                     num = sc.nextInt();

                                     break;

                            } catch (InputMismatchException e) {

                                               System.out.println("输入数据有误");

                                               System.out.println("请重新输入..");

                                               sc=new Scanner(System.in);//重置Scanner对象sc

                                               }

                                              

                                     }

                   System.out.println("刚才输入的整数是:"+num);

                            }

 

二:Scanner在while循环内的时候

public static void main(String[] args) {

                                      int num = 0;

                   while (true) {

                            try { 

Scanner sc = new Scanner(System.in);                      

                                     System.out.println("请输入整数..");

                                     num = sc.nextInt();

                                     break;

                            } catch (InputMismatchException e) {

                                               System.out.println("输入数据有误");

                                               System.out.println("请重新输入..");

                                               }

                                              

                                     }

                   System.out.println("刚才输入的整数是:"+num);

                            }

 

 
posted @ 2012-08-06 17:14  唔愛吃蘋果  阅读(7108)  评论(0编辑  收藏  举报