- import java.util.*;
- import javax.swing.*;
- import java.awt.*;
- public class ch54
- {
- public static void main(String args[]) throws BodyException //若要拋出自行定義的例外類別, 需在此註名
- {
- for(;;) //while(true)
- {
- float h,w;
- Scanner s=new Scanner(System.in);
- try
- {
- System.out.print("請輸入你的身高(公分): ");
- h=(s.nextFloat())/100;
- if(h*100<50 || h*100>220)
- throw new BodyException();
- System.out.print("請輸入你的體重(公斤): ");
- w=s.nextFloat();
- if(w<20 || w>200)
- throw new BodyException();
- System.out.println("你的BMI值為: "+w/(h*h));
- return;
- }catch(InputMismatchException e)
- {
- System.out.println("請輸入數字!");
- }catch(BodyException e)
- {
- e.run();
- }
- }
- }
- }
- class BodyException extends Exception
- {
- public BodyException()
- {
- super();
- }
- public void run()
- {
- JFrame f=new JFrame("Error");
- JButton bnt=new JButton("OK");
- f.setSize(120,100);
- f.getContentPane().add(bnt,BorderLayout.CENTER);
- f.setVisible(true);
- }
- }
複製代碼 |