Report#6(Java)

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

<1>

偶数奇数判定プログラム(GUIaa)をタイプし、その動作を考察せよ。

【GUIaa.javaのプログラム】

import java.awt.*;
import java.awt.event.*;                // GUI関係のパッケージクラス群をインポート

public class GUIaa extends Frame {      // Frameクラスの継承

    Button    b0 = new Button("Even/Odd?");                 //GUI部品のButtonを生成・初期化
    Label     x0 = new Label("Type a number and press..."); //GUIの部品Labelを生成&初期化
    TextField t0 = new TextField();                         //GUI部品のTextFieldを生成・初期化
    
    public GUIaa() {                              //コンストラクタでウィンドウの初期設定
        setLayout(null);                          //部品の自動配置機能を0FFにする。
        add(t0); t0.setBounds(10, 40, 90, 30);    // 入力欄の貼り付け(左上隅のx/y座標、幅、高さ)
        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(); //TextFieldの内容を読み込み
                t0.setText("");                                 //TextFieldを初期化
                if(i % 2 == 0) {                                //iが2で割り切れたら(偶数なら)
                    x0.setText(i + " is Even");                 //Labelに2is Even"と表示
                } else {                                        //そうでないなら(奇数なら)
                    x0.setText(i + " is Odd");                  //LabelにOddと表示
                    }
                }
            });
    }
public static void main(String[] args) {                  //mainメソッドが必要
    Frame win = new GUIaa();                              //前述のオブジェクトを、変数winへ生成・初期化
    win.setSize(200, 150); win.setVisible(true);          //表示するウインドウのサイズを指定
    win.addWindowListener(new WindowAdapter() {           //無名クラス・イベント
            public void windowClosing(WindowEvent evt) {  //ウインドウを閉じるときのイベント
                System.exit(0);                           //プログラムの終了。
                }
            });
    }
}

【実行結果】

●数字を入力する GUIaa.1 ●偶数の時 GUIaa.2 ●奇数の時 GUIaa.3

GUIプログラムとは

GUIコントロールクラス

ウィンドウ Frame
ダイアログウィンドウ Dialog
ボタン Button
チェックボックス CheckBox
1行テキストボックス TextField
複数テキストボックス TextArea
スクロースバー Scrollbar
メニューバー MenuBar
リストボックス List
ラベル Label
チョイス Choice
パネル Scrollpanel
Panel
Canvas
ポップアップメニュー PupupMenu

<2>

例外処理について、考察せよ。

【例外処理】

例外処理 たとえコンパイルできたとしても、ユーザーの思いがけない操作などで プログラムの実行中にプログラムが実行不可能になるような事象が起こります。 このような現象を例外とよぶ。 ※例外は、存在しないファイルを開こうとしたり、0で除算した時に起こる。
【0で除算したときのプログラム例 】
class test {
public static void main(String args[]) {
System.out.println(10 / 0);
}
}


【実行結果 】
[Daigo-WAKATSU:~/sites/java/Repo_6] j03064% javac test.java
[Daigo-WAKATSU:~/sites/java/Repo_6] j03064% java test
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at test.main(test.java:3)

0で除算した時に例外オブジェクトが生成されています。 java.lang.ArithmeticExceptionというのが、そのクラスです。 このような例外が発生するとプログラムは「割り込み」をします。 この場合は例外オブジェクトがプログラムに割り込んで、例外処理をして実行を停止させています。 例外処理は、このように例外が発生した時に割り込んで処理するプログラムです。 そこで、例外発生時に割り込むルーチンを定義することで、より上品に終わらせることができる。 例外の監視はtryステートメントで囲まれたブロックで行われる。 try { statements...; } tryブロックないのステートメントやメソッドで例外が発生すると プログラムはその例外の処理ができる処理班catchブロックを検索します catchブロックはtryブロックの後方に記述し、例外に備えます catch (ErrType1 param) { statements...; } catchは目的の例外処理に応じて任意の数だけ書けます。 ErrTypeには例外オブジェクトを指定します。 paramには例外のパラメータが入っています。 例外オブジェクトの種類がパラメータと一致した時そのcatchブロックが実行されます。 さらに例外処理はcatchブロックの終了、またはtryが終了した時に 制御がfinallyブロックへ移行して実行されるという特徴がある。 finallyは省略可能だが、リソースの解放などに使われる。 finally { statements...; } ※tryブロックの後には、からなずcatchブロックかfinallyブロックのいずれかが存在しなければいけない! (存在しなかった場合にはコンパイルエラーが発生する。)
【0で除算したときのプログラム例2】
class test2 {
    public static void main(String args[]) {
        try {
            System.out.println(10 / 0);
        }
        catch (ArithmeticException err) {
            System.out.println("エラー :" + err);
        }
        finally {
            System.out.println("終了。");
        }
    }
}


【実行結果 】
[nw0364:~/sites/java/Repo_6] j03064% java test2
エラー :java.lang.ArithmeticException: / by zero
終了。

こうすれば、catchブロックの処理が終了するとfinallyに制御が移ることがわかる。 _/_/_/まとめ_/_/_/

try

catch

finally

<3>

上述のサンプルプログラムに出てきたGUI部品を、全て使ったプログラムを作成せよ。

【GUI部品プログラム】

〜円の面積と円周を求める〜
import java.awt.*;
import java.awt.event.*;                // GUI関係のパッケージクラス群をインポート

public class Circle extends Frame {      // Frameクラスの継承

    static double total;

    Button    b0 = new Button("Calculate");                  //GUI部品のButtonを生成・初期化
    Label     x0 = new Label("_/_/_/Size of area circle & Circumferential length of circle_/_/_/");
    Label     x1 = new Label("(Type a number and choice and press...)"); 
    Label     x2 = new Label("Input Radius length  R=");     //GUIの部品Labelを生成&初期化
    Label     x3 = new Label("Answer");
    Label     x4 = new Label(" ");
    Label     x5 = new Label(" ");
    Choice    c0 = new Choice();                             //GUIの部品Choiceを生成&初期化
    TextField t0 = new TextField();                          //GUI部品のTextFieldを生成・初期化
    TextField t1 = new TextField();

    public Circle() {                                        //コンストラクタでウィンドウの初期設定
        setLayout(null);                                     //部品の自動配置機能を0FFにする。
        add(t0); t0.setBounds(200, 150, 90, 30);             //入力欄の貼り付け(左上隅のx/y座標、幅、高さ)
        add(t1); t1.setBounds(200, 230, 90, 30);
        add(b0); b0.setBounds(110, 190, 100, 30);            //ボタンの貼り付け
        add(c0); c0.setBounds(30, 100, 200, 30);             //チョイスの貼り付け
        c0.add("Size of area circle"); c0.add("Circumferential lentgh");
        add(x0); x0.setBounds(10, 40, 400, 30);              //表示欄の貼り付け
        add(x1); x1.setBounds(65, 70, 180, 30);
        add(x2); x2.setBounds(30, 150, 180, 30);
        add(x3); x3.setBounds(60, 230, 180, 30);
        add(x4); x4.setBounds(160, 230, 180, 30);
        add(x5); x5.setBounds(125, 270, 180, 30);

        b0.addActionListener(new ActionListener() {          //無名クラス、イベント
                public void actionPerformed(ActionEvent e) {

                    int a = c0.getSelectedIndex();

                    try{
                        int i = new
                            Integer(t0.getText()).intValue();
                        if (a == 0){
			total = i*i*3.14;                    //円周率は3.14とする。
                            x4.setText("S=");                //表示欄 x4 にS=と表示。
                        } else {
                            total = 2*3.14*i;
                            x4.setText("L=");                //表示欄 x4 にS=と表示。
                        }
                        t1.setText(total+"");                //入力欄 t1 にtotalの値を表示。
                    } catch(Exception ex) {                  //例外処理。
                        x5.setText("InputError!"); }         //入力欄 t1 にInputError!と表示。
                }
            });
    }

    public static void main(String[] args) {                  //mainメソッドが必要
        Frame win = new Circle();                             //前述のオブジェクトを、変数winへ生成・初期化
        win.setSize(420, 310); win.setVisible(true);          //表示するウインドウのサイズを指定
        win.addWindowListener(new WindowAdapter() {           //無名クラス・イベント
                public void windowClosing(WindowEvent evt) {  //ウインドウを閉じるときのイベント
                    System.exit(0);                           //プログラムの終了。
                }
            });
    }
}

【実行結果】

●数字を入力する 円の面積と円周
●円の面積を求める。 面積 ●円周の長さを求める。 円周
例外の場合
●数字以外を入れた時 数字以外 ●入力場所が違うとき 入力ミス

<4>

摂氏から華氏、華氏から摂氏への温度換算ができるプログラムを作成せよ。

【温度変換プログラム】

import java.awt.*;
import java.awt.event.*;// GUI関係のパッケージクラス群をインポート
 
public class Temp1 extends Frame {    // Frameクラスの継承

    static int total;

    Button     b0 = new Button("Calculate"); //GUI部品のButtonを生成・初期化
    Label      x0 = new Label("Changing machine"),
        x1 = new Label("(before)"),          //GUIの部品Labelを生成&初期化
        x2 = new Label("(after)"),
        x3 = new Label("");
    TextField  t0 = new TextField(),         //GUI部品のTextFieldを生成・初期化
        t1 = new TextField();
    Choice     c0 = new Choice();            //GUIの部品Choiceを生成&初期化

    public Temp1() {                                  //コンストラクタでウィンドウの初期設定
        setLayout(null);       //部品の自動配置機能を0FFにする。
        add(t0); t0.setBounds(10, 130, 90, 30);       //入力欄の貼り付け(左上隅のx/y座標、幅、高さ)
        add(t1); t1.setBounds(210, 130, 90, 30);
        add(c0); c0.setBounds(35, 70, 125, 30);       //チョイスの貼り付け
        c0.add("Sesshi >>> Kashi"); c0.add("Kashi >>> Sesshi");
        add(b0); b0.setBounds(105, 130, 100, 30);     //ボタンの貼り付け
        add(x0); x0.setBounds(10, 40, 180, 30);       //表示欄の貼り付け
        add(x1); x1.setBounds(10, 110, 80, 30);
        add(x2); x2.setBounds(210, 110, 80,30);
        add(x3); x3.setBounds(10, 170, 130, 30);

        b0.addActionListener(new ActionListener() {   //無名クラス、イベント
                public void actionPerformed(ActionEvent e) {

                    int a = c0.getSelectedIndex();

                    try {
                        int i = new
                        Integer(t0.getText()).intValue();
                        if (a == 0) {
                            total = i*9/5+32;         //摂氏から華氏は、i*1.8+32で計算。
                            x3.setText("");
                        } else {
			total = (i-32)*5/9;           //華氏から摂氏は、(i-32)/1.8で計算。
                            x3.setText("");
                        }
                        t1.setText(total+"");//入力欄にtotalの値を表示。
                    } catch(Exception ex) {//例外処理。
                        x3.setText("InputError!"); }  //表示欄x3に InputError!と表示。

                }
            });
    }

    public static void main(String[] args) {                //mainメソッド。
        Frame win = new Temp1();                            //前途のオブジェクトを変数winへ生成、初期化。
        win.setSize(340, 250);                              //表示するウィンドウのサイズを指定。
        win.setVisible(true);
        win.addWindowListener(new WindowAdapter() {         //無名クラス・イベント
                public void windowClosing(WindowEvent evt) {//ウィンドウを閉じる時のイベント
                    System.exit(0);                         //プログラムの終了。
                }
            });
    }
}

【実行結果】

●数字を入力する Calculate
●摂氏から華氏への変換 Sessikasi ●華氏から摂氏への変換 Kasisessi
※ボタン、ラベル、テキストフィールド、チョイスを使ってやってみた。

<5>

「電卓」プログラムを作成せよ。中身は自分の思うように。

【Calculate.javaのプログラム】

import java.awt.*;
import java.awt.event.*;               // GUI関係のパッケージクラス群をインポート

public class Calculate extends Frame { //Frameクラスの継承
    Button b0 = new Button("a+b");     //GUI部品のButtonを生成・初期化
    Button b1 = new Button("a-b");
    Button b2 = new Button("a/b");
    Button b3 = new Button("a*b");
    Button b5 = new Button("AC");
    Label x0 = new Label("");          //GUIの部品Labelを生成&初期化
    Label x1 = new Label("_/_/_/_/_/  Calculating Machine  _/_/_/_/_/");
    Label x2 = new Label("");
    Label x3 = new Label("( a )");
    Label x4 = new Label("( b )");
    TextField t0 = new TextField();    //GUI部品のTextFieldを生成・初期化
    TextField t1 = new TextField();
    TextField t2 = new TextField();

    public Calculate() {                         //コンストラクタでウィンドウの初期設定
    setLayout(null);                             //自動配置をしない
        add(t0); t0.setBounds(30, 90, 100, 30);  //TextFieldの貼り付け
	add(t1); t1.setBounds(165, 90, 100, 30);
        add(t2); t2.setBounds(70, 205, 200, 30);
        add(b0); b0.setBounds(75, 135, 60, 30);  //ボタンの貼り付け
        add(b1); b1.setBounds(150, 135, 60, 30);
        add(b2); b2.setBounds(150, 170, 60, 30);
        add(b3); b3.setBounds(75, 170, 60, 30);
        add(b5); b5.setBounds(110, 250, 80, 30);
        add(x0); x0.setBounds(10, 205, 90, 50);  //表示欄の貼り付け
        add(x1); x1.setBounds(10, 40, 200, 30);
        add(x2); x2.setBounds(30, 253, 200, 30);
        add(x3); x3.setBounds(60, 70, 90, 50);
        add(x4); x4.setBounds(190, 70, 90, 50);

        b0.addActionListener(new ActionListener() {      //Button+を押したときのイベント処理
                    public void actionPerformed(ActionEvent evt) {
                    try {
                        int i = (new
                    Integer(t0.getText())).intValue();
                        int j = (new
                    Integer(t1.getText())).intValue();
                        x0.setText("Result");
                        t2.setText("" + (i+j) + "");
			}catch(NumberFormatException ne) { //数字以外を代入したときの例外処理
                        x0.setText("Error");
                    }
                }
            });

        b1.addActionListener(new ActionListener() {      //-を押したときのイベント処理
                    public void actionPerformed(ActionEvent evt) {
                    try { 
                        int i = (new
	   Integer(t0.getText())).intValue();
                        int j = (new
	   Integer(t1.getText())).intValue();
                        x0.setText("Result");
                        t2.setText("" + (i-j) + "");
                    }catch(NumberFormatException ne) {     //数字以外を代入したときの例外処理
                        x0.setText("Error");
                    }
                }
            });

        b2.addActionListener(new ActionListener() {        //-を押したときのイベント処理
                public void actionPerformed(ActionEvent evt) {
                    try {                                  //例外処理
                        int i = (new
                        Integer(t0.getText())).intValue();
                        int j = (new
                        Integer(t1.getText())).intValue();
                        x0.setText("Relult");
                        t2.setText("" + i/j + "");
                    }catch(NumberFormatException ne) {     //数字以外を代入したときの例外処理
                        x0.setText("Error");
                    }
                }
            });

        b3.addActionListener(new ActionListener() {        //*を押したときのイベント処理
                    public void actionPerformed(ActionEvent evt) {
                    try {                                  //例外処理
                        int i = (new
                    Integer(t0.getText())).intValue();
                        int j = (new
                    Integer(t1.getText())).intValue();
                        x0.setText("Result");
	   t2.setText("" + i*j + "");
                    }catch(NumberFormatException ne){      //数字以外を代入したときの例外処理
                        x0.setText("Error");
                    }
                }
            });

        b5.addActionListener(new ActionListener() {        //ACを押したときのイベント処理
                    public void actionPerformed(ActionEvent evt) {
                    x2.setText("ALL CLAER");
                    t0.setText("");
                    t1.setText("");
                    t2.setText("");
                }
            });
    }

    public static void main(String[] args) {                 //mainメソッド
        Frame win = new Calculate();                         //フレームのインスタンス化
        win.setSize(300, 300); win.setVisible(true);         //サイズ設定
        win.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) { //ウィンドウを閉じるときのイベント処理
                    System.exit(0);
                }
            });
    }
}

【実行結果】

●数字を入力する Calculating machine
●123*321の計算 123*321 ●123-321の計算 123-321
●数字以外を入力したとき 123*321 ●AC(ALL CREAR) ALL CLEARする。

【感想】

 今回の課題は、GUIということで楽しく取り組めた方だと思う...。もっと余裕 をもってゆっくりやってみたいと思った。  最近、課題を終わらせていつも思います...そろそろJavaちゃんと頑張ってみようかなぁ。。

【参考文献・URL】

・浅煎り珈琲〜Java アプリケーション入門 (http://msugai.fc2web.com/java/#objective) ・JAVA言語入門 (http://black.sakura.ne.jp/~third/programming/java/java.html) ・Java入門 (http://www5c.biglobe.ne.jp/~ecb/java/java00.html)