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);

                            }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM