top > Programing2 Report5



課題内容
  1. 偶数奇数判定プログラム(GUIaa)をタイプし、その動作を考察せよ。
  2. 例外処理について、考察せよ。
  3. 上述のサンプルプログラムに出てきたGUI部品を、全て使ったプログラムを作成せよ。
  4. 摂氏から華氏、華氏から摂氏への温度換算ができるプログラムを作成せよ。。
  5. 「電卓」プログラム。中身は自分の思うように。


    目次
    1. 偶数奇数判定プログラムと実行結果

    2. 例外処理構文

    3. GUI部品を使ったプログラム

    4. 温度換算プログラム

    5. 電卓プログラム

    6. まとめ
    7. 参考文献・参考Webページ



    1. 偶数奇数判定プログラム
      • ソース
        import java.awt.*;
        import java.awt.event.*;
        
        public class GUIaa extends Frame {
            Button    b0 = new Button("Even/Odd?");
            Label     x0 = new Label("Type a number and press...");
            TextField t0 = new TextField();
        
            public GUIaa() {
                setLayout(null);
                add(t0); t0.setBounds(10, 40, 90, 30);
                add(b0); b0.setBounds(110, 40, 80, 30);
                add(x0); x0.setBounds(10, 80, 180, 30);
                b0.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            int i = (new Integer(t0.getText())).intValue();
                            t0.setText("");
                            if(i % 2 == 0) {
                                x0.setText(i + " is Even");
                            } else {
                                x0.setText(i + " is Odd");
                            }
                        }
                    });
            }
            public static void main(String[] args) {
                Frame win = new GUIaa();
                win.setSize(200, 150); win.setVisible(true);
                win.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent evt) {
                            System.exit(0);
                        }
                    });
            }
        }
        

      • 実行結果

      • ソースの考察
        ln.5(〜7)
        Button    b0 = new Button("Even/Odd?");
        Label     x0 = new Label("Type a number and press...");
        TextField t0 = new TextField();
        Even/Odd?ボタンを作成、
        表示欄を作成しType a number and pressを表示、
        入力欄を作成する
        これらは、コンポーネントと呼ばれ、GUI(Graphical User Interface)の部品。
        
        ln.10~13
        setLayout(null);
        add(t0); t0.setBounds(10, 40, 90, 30);
        add(b0); b0.setBounds(110, 40, 80, 30);
        add(x0); x0.setBounds(10, 80, 180, 30);
        10行目でGUI部品の自動配置機能を切り、(nullにした。)
        パーツを自由に配置できるようにした。
        t0,x0,t0はそれぞれボタン、結果表示欄、入力欄。
        11~13行目でこの3つの位置を配置している
        setBoundsの中は(x,y,w,h)の順に入れる。
        
        ln.14~21
        public void actionPerformed(ActionEvent evt) {
        int i = (new Integer(t0.getText())).intValue();
        t0.setText("");
        if(i % 2 == 0) {
        x0.setText(i + " is Even");
        } else {
        x0.setText(i + " is Odd");
        この行では、イベントが起きた時に(例えばボタンを押したときなど)
        どういう対処をするかを設定している。
        まず、入力欄に入っている数列を呼び出してint i に格納し
        入力欄を空にする。l
        if文内では、
        i が2で割り切れるとき"i is Even" つまり i は偶数であると表示欄に表示させる。
        elseでそれ以外の場合の処理を決定する。
        今回は、" i is Odd "、つまり i は奇数であると表示欄に表示させる。
        
        ln.26~31
        public static void main(String[] args) {
        Frame win = new GUIaa();
        win.setSize(200, 150); win.setVisible(true);
        win.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent evt) {
        System.exit(0);
        ここでは、Frameを設置して、GUIaaを入れる。
        Frameは実行時に表示される窓のこと。
        ln28では、Frameの大きさを設定し、表示させている。
        WindowListenerはウィンドウの変化をキャッチし監視します。
        そこで、WindowListenerを使い、ウィンドウが閉じるとき
        (WindowClosingの時)正常に終了するように設定します。
        


    2. 例外処理とは
      • 例外処理構文
        try {
             (例外を発生する可能性のある処理)
        }
        catch (例外のタイプ1 変数名){
            (例外のタイプ1が発生した時の処理)
        }
        catch (例外のタイプ2 変数名){
             (例外のタイプ2発生した時の処理)
        }
                     :
        catch (例外のタイプn 変数名){
             (例外のタイプnが発生した時に処理)
        }
        finally {
             (例外発生の有無に関わらず必ず実行する処理)
        }
        
      • 例外処理について
        Java では、プログラムを実行する最中に発生するエラーを
        例外(exception)として扱うことができます。
        例外には例えば、0で割り算をした、メモリが枯渇した、
        存在しないファイルを開こうとしたなどがあります。
        例外オブジェクトは、次のような構想をもっています。
        
        そこで、以上のような例外を処理する方法として、
        try・catch文があります。
        tryで例外の起ると思われる処理を囲み、
        catchで例外が起きた場合の処理方を特定します。
        他には、throwsを使い、あらかじめ例外が起きるであろうと
        予測されることをプログラムに知らせる方法もあります。
        この場合は、try・catch文も使わなければ
        コンパイル時にエラ−が起きます。
        


    3. GUI部品を使ったプログラム
      • ソース
        import java.awt.*;
        import java.awt.event.*;
        public class Prof2 extends Frame{
            Button     b0 = new Button("make your profile");
            Button     b1 = new Button("add your hobby to the list");
            TextField  t0 = new TextField();
            TextField  t1 = new TextField();
            TextField  t3 = new TextField();
            TextArea   t2 = new TextArea("youre profile will show here.");
            Label      l0 = new Label("enter your name");
            Label      l1 = new Label("check your sex");
            Label      l2 = new Label("enter your hobby");
            Label      l3 = new Label("choose the place you live");
            Label      l4 = new Label("enter your birthday");
            Label      l5 = new Label("hobby list");
            Checkbox[] cb = new Checkbox[]{new Checkbox("boy"), new Checkbox("girl")};
            Choice     c0 = new Choice();
            List       l6 = new List();
            public Prof2() {
        	setLayout(null);
        	add(l0); l0.setBounds(10, 30, 300, 20);
                add(t0); t0.setBounds(10, 60, 300, 20);
                add(l1); l1.setBounds(10, 90, 300, 20);
                add(cb[0]); cb[0].setBounds(10, 120, 80, 20);
                add(cb[1]); cb[1].setBounds(100, 120, 80, 20);
        	add(l4); l4.setBounds(10, 150, 300, 20);
        	add(t1); t1.setBounds(10, 180, 300, 20);
                add(l3); l3.setBounds(10, 210, 300, 20);
                add(c0); c0.setBounds(10, 240, 300, 20);
        	c0.add("Ryudai"); c0.add("Okinawa");
        	c0.add("Japan");  c0.add("earth");
        	c0.add("space");  c0.add("Other");
                add(l2); l2.setBounds(10, 270, 300, 20);
                add(t3); t3.setBounds(10, 300, 300, 20);
        	add(b1); b1.setBounds(10, 330, 300, 20);
        	add(b0); b0.setBounds(10, 360, 300, 20);
        	add(t2); t2.setBounds(10, 390, 300, 100);
        	add(l5); l5.setBounds(320, 30, 100, 20);
        	add(l6); l6.setBounds(320, 60, 100, 430);
        	b1.addActionListener(new ActionListener(){
        		public void actionPerformed(ActionEvent evt){
        		    String hobby = (new String(t3.getText()));
        		    l6.add(""+ hobby);
        		}
        	    });
        	b0.addActionListener(new ActionListener(){
        		public void actionPerformed(ActionEvent evt){
        		    try{
        			String name = (new String(t0.getText()));
        			String btdy = (new String(t1.getText()));
        			t2.setText("profile...\n");
        			t2.append("name     : "+ name + "\n");
        			if(cb[0].getState()){
        			    t2.append("sex      : boy" + "\n");
        			}else{
        			    t2.append("sex      : girl\n");
        			}
        			t2.append("birthday : "+ btdy + "\n");
        			if(c0.getSelectedIndex() == 0){
        			    t2.append("living : Ryudai");
        			}else if(c0.getSelectedIndex() == 1){
        			    t2.append("living : Okinawa");
                                }else if(c0.getSelectedIndex() == 2){
        			    t2.append("living : Japan");
                                }else if(c0.getSelectedIndex() == 3){
        			    t2.append("living : OutSea");
                                }else if(c0.getSelectedIndex() == 4){
        			    t2.append("living : Space");
        			}else{
        			    t2.append("living : Other");}
        		    }catch(Exception e){
        			t2.setText("Errow was found.");
        		    }
        		}});
            }
            public static void main (String [] args){
        	Frame win = new Prof2();
        	win.setTitle ("easy profile making");
        	win.setSize(450,500);
        	win.setVisible(true);
        	win.addWindowListener( new WindowAdapter(){
        		public void windowClosing(WindowEvent evt){
        		    System.exit(0);
        		}
        	    });
            }
        }
        

      • 実行結果

      • ソースの考察
        ln.4~18
        ボタンを2つ、テキストフィールドを3つ、テキストエリアを1つ、
        ラベルを6つ、チェックボックスを2つ、
        プルダウンメニューを1つ、リストを1つ作成。
        
        ln.16
        Checkbox[] cb = new Checkbox[]{new Checkbox("boy"), new Checkbox("girl")};
        配列で、Checkboxを2つ作る。(boyとgirl)
        
        ln.20~38
        ボタン、テキストフィールド、テキストエリア、
        ラベル、チェックボックス、プルダウンメニュー、リストの位置をそれぞれ決定する。
        
        ln.29~32
        add(c0); c0.setBounds(10, 240, 300, 20);
        c0.add("Ryudai"); c0.add("Okinawa");
        c0.add("Japan");  c0.add("earth");
        c0.add("space");  c0.add("Other");
        プルダウンメニューの選択肢に6つ選択肢を追加。
        
        ln.39~44
        	b1.addActionListener(new ActionListener(){
        		public void actionPerformed(ActionEvent evt){
        		    String hobby = (new String(t3.getText()));
        		    l6.add(""+ hobby);
        		}
        	    });
        b1ボタン(趣味ボタン)を押した時の動作を設定する。
        hobbyにt3に入力した文字列を取り込み、
        l6(趣味リスト)に追加する。
        
        ln.45~74
        b0ボタンを押した時の動作を設定する。
        
        ln.47~50
        String name = (new String(t0.getText()));
        String btdy = (new String(t1.getText()));
        t2.setText("profile...\n");
        t2.append("name     : "+ name + "\n");
        name にt0に入力した文字列を入れる。
        btdyにt1に入力した文字列を入れる。
        t2(テキストエリア)にprofile...と出力し、改行する。
        続いて、appendでt2に"name     : "+ name + "\n"を追加する。
        
        ln.51~55
        if(cb[0].getState()){
            t2.append("sex      : boy" + "\n");
        }else{
            t2.append("sex      : girl\n");
        }
        cb[0] (boyのボックス)がチェックされていた場合に
        if文の内容を実行。
        if文の内容は"sex      : boy" + "\n"をt2に出力すること。
        もし、boyがチェックされてない場合は
        "sex      : girl\n"を追加する。
        よって、何もチェックされていない場合はgirlが表示され、
        両方がチェックされている場合はboyが表示される。
        
        ln.56~69
        プルダウンメニューで選択した選択肢をt2に追加する。
        
        
        Frame win = new Prof2();
        win.setTitle ("easy profile making");
        win.setSize(450,500);
        win.setVisible(true);
        win.addWindowListener( new WindowAdapter(){
        public void windowClosing(WindowEvent evt){
        System.exit(0);
        Prof2クラスのオブジェクトを呼び出す。
        setTitleでウィンドウのタイトルをeasy profile makingに設定。
        setSizeでウィンドウの大きさを設定。
        setVisivleでウィンドウが見えるようにする。
        addWindowListener内で、正常に終了するように設定。
        


    4. 温度換算プログラム
      • ソース
        import java.awt.*;
        import java.awt.event.*;
        public class fc extends Frame {
            Button    btn = new Button("change");
            Choice    foc = new Choice();
            Label     lab = new Label("Type a number correctly.");
            TextField tex = new TextField();
            public fc() {
                setLayout(null);
                add(tex); tex.setBounds(10, 40, 90, 25);
                add(foc); foc.setBounds(10, 80, 180, 30);
                foc.add("Celsius -> Fahrenheit");
                foc.add("Fahrenheit -> Celsius");
                add(btn); btn.setBounds(210, 80, 30, 30);
                add(lab); lab.setBounds(10, 120, 250, 30);
                btn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt){
                            try {
                                double r = (new Double(tex.getText())).doubleValue();
                                if(foc.getSelectedIndex() == 0) {
                                    r = 5f/9f*r+32f;
                                }else{
        						r = 5f/9f*(r-32);
                                };
                                lab.setText("" + r );
                            }catch(Exception e){
                                tex.setText("");
                                lab.setText("error was found. Type agan correctly.");
                            }
                        }
                    } );
            }
            public static void main (String [] args) {
                Frame win = new fc();
                win.setTitle("Celsius <-> Fahrenheit");
                win.setSize(250, 160);
                win.setVisible(true);
                win.addWindowListener( new WindowAdapter() {
                        public void windowClosing(WindowEvent evt){
                            System.exit(0);
                        }
                    } );
            }
        }
        

      • 実行結果

      • ソースの考察
        ln.4~7
        Button    btn = new Button("change");
        Choice    foc = new Choice();
        Label     lab = new Label("Type a number correctly.");
        TextField tex = new TextField();
        ボタン、プルダウンメニュー、ラベル、テキストフィールドを作成。
        ボタンには"change"という文字を入れ、
        ラベルには"Type a number correctly."と入れる
        
        ln.9~15
        setLayout(null);
        add(tex); tex.setBounds(10, 40, 90, 25);
        add(foc); foc.setBounds(10, 80, 180, 30);
        foc.add("Celsius -> Fahrenheit");
        foc.add("Fahrenheit -> Celsius");
        add(btn); btn.setBounds(210, 80, 30, 30);
        add(lab); lab.setBounds(10, 120, 250, 30);
        レイアウトの設定。
        自由に設定できるようにsetLayoutをnullにする。
        テキスト、プルダウンメニュー、
        ボタン、ラベルの位置を設定し、
        (ln.11,12)選択肢を2つ追加する。
        
        ln.16~29
        btn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt){
        try {
        double r = (new Double(tex.getText())).doubleValue();
        if(foc.getSelectedIndex() == 0) {
        r = 5f/9f*r+32f;
        }else{
        r = 5f/9f*(r-32);
        };
        lab.setText("" + r );
        }catch(Exception e){
        tex.setText("");
        lab.setText("error was found. Type agan correctly.");
        }
        ボタンを押した後の動作を設定。
        try catch文でエラーが発生したらラベルに文を表示するように設定。
        rに入力した数字を入れる。
        もし、0番目のCelsius -> Fahrenheitを選択していたら
        5f/9f*r+32f を計算し、rに入れる。
        もし、他を選択していた場合、(今回の場合はFahrenheit -> Celsius)
        5f/9f*(r-32) を計算し、rに入れる。
        計算した後、rを表示。
        
        ln.34~40
        Frame win = new fc();
        win.setTitle("Celsius <-> Fahrenheit");
        win.setSize(250, 160);
        win.setVisible(true);
        win.addWindowListener( new WindowAdapter() {
        public void windowClosing(WindowEvent evt){
        System.exit(0);
        fcクラスのオブジェクトを呼び出す。
        setTitleでウィンドウのタイトルをCelsius <-> Fahrenheitに設定。
        setSizeでウィンドウの大きさを設定。
        setVisivleでウィンドウが見えるようにする。
        addWindowListener内で、正常に終了するように設定。
        


    5. 電卓プログラム
      • ソース
        import java.awt.*;
        import java.awt.event.*;
        public class Den extends Frame{
            Button    add = new Button("+");
            Button    sub = new Button("-");
            Button    mul = new Button("*");
            Button    div = new Button("/");
            Button    ac  = new Button("AC");
            Button    equ = new Button("=");
            Button    lef = new Button("%");
            TextField tex = new TextField();
            TextField ans = new TextField("0");
            Label     dsp = new Label("Enter a number.");
            public Den(){
                setLayout(null);
                add(tex); tex.setBounds(10, 30, 200, 20);
                add(add); add.setBounds(10, 90, 20, 20);
                add(sub); sub.setBounds(40, 90, 20, 20);
                add(mul); mul.setBounds(70, 90, 20, 20);
                add(div); div.setBounds(10, 120, 20, 20);
                add(equ); equ.setBounds(40, 120, 20, 20);
                add(lef); lef.setBounds(70, 120, 20, 20);
                add(ac);   ac.setBounds(10, 150, 90, 20);
                add(ans); ans.setBounds(10, 60, 200, 20);
                add(dsp); dsp.setBounds(10, 180, 200, 20);
        
                try{
                    add.addActionListener(new ActionListener(){
                            public void actionPerformed(ActionEvent evt){
                                int a = (new Integer(tex.getText())).intValue();
                                int b = (new Integer(ans.getText())).intValue();
                                b = a + b;
                                tex.setText("");
                                ans.setText("" + b);
                            }
                        });
                    sub.addActionListener(new ActionListener(){
                            public void actionPerformed(ActionEvent evt){
                                int a = (new Integer(tex.getText())).intValue();
                                int b = (new Integer(ans.getText())).intValue();
                                b = a - b;
                                tex.setText("");
                                ans.setText("" + b);
                            }
                        });
                    mul.addActionListener(new ActionListener(){
                            public void actionPerformed(ActionEvent evt){
                                int a = (new Integer(tex.getText())).intValue();
                                int b = (new Integer(ans.getText())).intValue();
                                b = a * b;
                                tex.setText("");
                                ans.setText("" + b);
                            }
                        });
                    div.addActionListener(new ActionListener(){
                            public void actionPerformed(ActionEvent evt){
                                int a = (new Integer(tex.getText())).intValue();
                                int b = (new Integer(ans.getText())).intValue();
                                b = a / b;
                                tex.setText("");
                                ans.setText("" + b);
                            }
                        });
                    lef.addActionListener(new ActionListener(){
                            public void actionPerformed(ActionEvent evt){
                                int a = (new Integer(tex.getText())).intValue();
                                int b = (new Integer(ans.getText())).intValue();
                                b = a % b;
                                tex.setText("");
                                ans.setText("" + b);
                            }
                        });
                    equ.addActionListener(new ActionListener(){
                            public void actionPerformed(ActionEvent evt){
                                int b = (new Integer(ans.getText())).intValue();
                                dsp.setText("Answer is " + b);
                                ans.setText("0");
                                tex.setText("");
                            }
                        });
                    ac.addActionListener(new ActionListener(){
                            public void actionPerformed(ActionEvent evt){
                                tex.setText("");
                                ans.setText("0");
                                dsp.setText("Enter a number.");
                            }
                        });
                }catch(Exception e){
                    dsp.setText("Errow was found. press ac and try again");
                }
            }
            public static void main(String [] args){
                Frame win = new Den();
                win.setTitle("Dentaku");
                win.setSize(220,220);
                win.setVisible(true);
                win.addWindowListener(new WindowAdapter(){
                        public void windowClosing(WindowEvent evt){
                            System.exit(0);
                        }
                    });
            }
        }
        

      • 実行結果
           
      • ソースの考察
        ln.4~13
            Button    add = new Button("+");
            Button    sub = new Button("-");
            Button    mul = new Button("*");
            Button    div = new Button("/");
            Button    ac  = new Button("AC");
            Button    equ = new Button("=");
            Button    lef = new Button("%");
            TextField tex = new TextField();
            TextField ans = new TextField("0");
            Label     dsp = new Label("Enter a number.");
        ボタンを7つ設定。
        テキストフィールドを2つ設定。
        ラベルを一つ設定。
        
        ln.15~25
                setLayout(null);
                add(tex); tex.setBounds(10, 30, 200, 20);
                add(add); add.setBounds(10, 90, 20, 20);
                add(sub); sub.setBounds(40, 90, 20, 20);
                add(mul); mul.setBounds(70, 90, 20, 20);
                add(div); div.setBounds(10, 120, 20, 20);
                add(equ); equ.setBounds(40, 120, 20, 20);
                add(lef); lef.setBounds(70, 120, 20, 20);
                add(ac);   ac.setBounds(10, 150, 90, 20);
                add(ans); ans.setBounds(10, 60, 200, 20);
                add(dsp); dsp.setBounds(10, 180, 200, 20);
        ボタン等の位置を決定。
        
        ln.27~63
        try{
        add.addActionListener(new ActionListener(){
        			public void actionPerformed(ActionEvent evt){
        						・
        						・
        						・
        ボタンを押した時の動作を設定。
        ln.28~43までは、aの値をbの値と足したり割ったりする。
        ln.46~60までは、値を消したり、結果を表示したりする。
        ln.61~63は、エラーが発生したら文を出力する。
        
        ln90~end
        Frame win = new Den();
        win.setTitle("Dentaku");
        win.setSize(220,220);
        win.setVisible(true);
        win.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent evt){
        System.exit(0);
        Denクラスのオブジェクトを呼び出す。
        setTitleでウィンドウのタイトルをDentakuに設定。
        setSizeでウィンドウの大きさを設定。
        setVisivleでウィンドウが見えるようにする。
        addWindowListener内で、正常に終了するように設定。
        
    6. まとめ・感想
      楽しかったです!!!
      特に、自分でほとんどやったのは終った後に充実感がありました。
      でも、考察はほぼ似たようなことしか書けずにちょっと苦労しました。
      そして・・・全体的に長くなりました。
      温度変換のプログラムはこれからも使えそうで、
      っていうか、早速海外の友人に今の気温伝えるために使えて助かりました。
      計算機のプログラムは、ボタンを使わずに作ろうとしたら、
      あまり無いタイプのやつになりました。
      使い慣れたら使いやすいプログラムだと思います。
      プロフィールのプログラムは、2つ作って2番目の奴を載せました。
      1番目のは、全く同じことをするのですが、異様に長いものになってしまったので、
      2番目はその改良版になりました。
      とてもすっきりして見やすくなったと思います。
      


    7. 参考文献・参考サイト








    Copyright since-2006 j06008 All rights reserved.