10. สิ่งผิดปกติ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 10-1  เมท็อดอ่านจำนวนถัดไปจากตัวอ่าน sc (จะอ่านข้ามข้อมูลที่ไม่ใช่จำนวน)
  public static double readDouble(Scanner sc, String msg) {
    double v = 0;
    boolean success = false;
    do {
      try {
        if (!"".equals(msg)) System.out.print(msg);      
         v = sc.nextDouble();
         success = true;  // ทำสำเร็จแล้ว 
       } catch (InputMismatchException e) {
         if (!"".equals(msg))  
           System.out.println("ต้องใส่จำนวนจึงจะทำงานถูกต้อง กรุณาป้อนใหม่");
        sc.next();       // อ่านข้อมูลที่ผิดนั้นทิ้งไป 
      }
    } while( !success );  // ยังไม่สำเร็จ วนกลับไปทำใหม่ 
    return v;
  }
©2009 S.Prasitjutrakul