問題


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

ソースプログラム
import java.awt.*;
import java.awt.event.*;              ----------(1)

public class GUIaa extends Frame {         ----------(2) 
 Button b0 = new Button("Even/Odd?"); 
 Label x0 = new Label("Type a number and press..."); -------(3)
 TextField t0 = new TextField();

 public GUIaa() {
  setLayout(null);                ----------(4)
  add(t0); t0.setBounds(10, 40, 90, 30);
  add(b0); b0.setBounds(110, 40, 80, 30);    ----------(5)
  add(x0); x0.setBounds(10, 80, 180, 30);
  b0.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent evt) {
    int i = (new Integer(t0.getText())).intValue();  ---(6)
    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);  ----------(7)
  win.addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent evt) {
    System.exit(0);
   }
  });
 }
}

実行結果
 

考察
(1) java.awtパッケージとjava.awt.eventパッケージをimportしている。
  import java.awt.*でjava.awt内のすべてのクラスは参照できるようになるが
  java.awt中のパッケージ内のクラスまでは参照することはできない。
  そのため、さらにimport java.awt.event.*を記述している。


(2) ウインドウを作成するためにFrameクラスを継承したサブクラスGUIaaを作っている。


(3) Buttonクラス、Labelクラス、TextFieldクラスのインスタンスを作り
  それぞれb0,x0,t0に代入している。これらはコンポーネントと呼ばれるGUIの部品である。


(4) GUI部品の自動配置機能をオフにして手動で配置するようにしている。


(5) コンテナと呼ばれるコンポーネントを配置できるコンポーネントに
  addメソッドを使用してButton等のGUI部品を格納している。
  その後、setBoundsで実際に配置する座標と大きさを指定している。


(6) int i = (new Integer(t0.getText())).intValue;を書き換えるとこうなる。
     String  s = t0.getText;
     Integer in = new Integer(s);
     int   i = in.intValue;
  t0.getTextメソッドはt0に入力された文字列を値として返す。
  intValueメソッドはIntegerクラスのメソッドで、
  インスタンス作成時に引数として与えられた文字列(整数)をint型の数に変換して返す。
  つまりこの文はTextField t0に入力された整数の文字列を
  int型の数に変換してint iに代入するという意味である。


(7) Frame型の変数winにGUIaaクラスのインスタンスを代入している。
  GUIaaクラスはFrameクラスを継承して作ったサブクラスなので代入が可能である。
  setSizeメソッドでウインドウの大きさを指定し、setVisible(true)でウインドウを見えるようにする。

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

ソースプログラム
class Reigai {

        public static void main(String args[]){
                
                try{
                        System.out.println("1");
                        int i= Integer.parseInt(args[0]);
                        int j= Integer.parseInt(args[1]);
                        System.out.println(i/j);
                        System.out.println("2");
                }
                catch(ArithmeticException e){  //----------(1)
                        System.out.println("3");
                }
                catch(ArrayIndexOutOfBoundsException e){ //----(2)
                        System.out.println("4"+"5");
                }
                catch(NumberFormatException e){ //------(3)
                        System.out.println("6");
                }
                finally{                       //-------(4)(5)(6)(7)
                        System.out.println("7");
                }
        }
}

実行結果
1
45
7

考察
要点まとめ
コンパイル時には発見されずに、インタープリタで実行する段階で発生するエラーのことを 例外と呼ぶ。例外は、変数にデータ型が違う値を入れようとしたり、 抽象クラスをインスタンス化しようとしたりした時に発生する。 例外が発生すると、その例外の種類に対応した型のオブジェクトが作成される。 tryとcatchを使って例外が発生した時に処理することを例外処理という。
Exeptionクラス→Throwableクラスを拡張。 実行時に発生する可能性がある様々な問題を表すサブクラスがある。 Exceptionクラスの主なサブクラス(java.langパッケージに定義されている。)  
クラス 説明
ClassNotFoundException クラスが見つからなかった
IllegalAccessException クラスに不正アクセスしようとした
InstantiationException インターフェイスまたは抽象クラスをインスタンス化しようとした
InterruptedException スレッドに割り込みが入った
NoSuchFieldException フィールドが見つからなかった
NoSuchMethodException メソッドが見つからなかった
RuntimeException 実行時に例外が発生した
RuntimeExeptionクラス→Exceptionの最も重要なサブクラス。 プログラムの実行中に発生する頻度が高い問題を表す。 RuntimeExceptionのサブクラス
クラス 説明
ArrayIndexOutOfBoundsException 配列のインデックスが実在しない要素を指していた
ArithmeticException 算術例外が発生(整数を0で除算した場合など)
ClassCastException 不正なキャスト操作を試みた
NegativeArraySizeException 配列のサイズとして負の値を使った
NullPointerException 空のオブジェクトのフィールドまたはメソッドにアクセスを試みた
NumberFormatException 整数の形式が不正だった
SecurityException セキュリティ違反のため操作が拒否された
StringIndexOutOfBoundsException 文字列のインデックスが文字列の領域をはみ出した


プログラムの考察
(1)Javaでは、あらゆる種類の「想定外の事柄」(エラー等)は全て例外(exception)と呼ばれる動作の発生によって通知される。 (2)例外が発生する典型的なケース 整数を0で除算した 配列のインデックスが負の値または配列の領域を超える値 ファイルが見つからなくなった 数値の形式が不正 など。 (3)例外発生したときの処理 try{ ・・・例外が発生する可能性のある処理・・・ } catch(Exception ex){ ・・・例外時の処理・・・ } (4)tryステートメントでは、処理ブロックを中括弧({})で囲む。 この部分に、例外の発生を監視する必要があるコードを記述する。 このコードの実行中に問題が起こった場合、例外が投げられる。 (5)catchステートメントでは、引数が受け取られる。 この引数は発生した問題に関する情報を格納した例外オブジェクト。 (6)tryブロック内のコードを実行している時に問題が発生した場合、 tryブロックの実行を停止し、その種類の例外を処理できるcatchブロックを検索する。 例外オブジェクトの種類がcatchブロックのパラメータと一致した場合は、その処理が実行される。 一致しなければ、次のcatch節に検索が進められる。 (7)tryブロックには、少なくとも1つのcatchブロックかfinallyブロックが必要。 そうでなければ、コンパイルエラーが発生する。 (8)getMessage()メソッド→コンストラクタから提供された文字列を返す。

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

ソースプログラム
import java.awt.*;
import java.awt.event.*;

public class GUId extends Frame{
 Button b0 = new Button();
 TextField t0 = new TextField();
 Label l0 = new Label("");
 TextArea ta0 = new TextArea("");
 Checkbox cb0 = new Checkbox();       -------------(1)
 Choice ch0 = new Choice();
 List ls0 = new List();

 public GUId(){
  setLayout(null);
  add( b0); b0.setBounds(130, 30, 70, 30);
  add( t0); t0.setBounds( 50, 80,150, 15);
  add( l0); l0.setBounds( 50, 60,150, 30);
  add(ta0); ta0.setBounds( 50, 110,150, 80);
  add(cb0); cb0.setBounds(110, 30, 30, 30);

  ch0.add("1"); ch0.add("2"); ch0.add("3");
  ch0.add("4"); ch0.add("5"); ch0.add("6"); -------------(2)
  add(ch0); ch0.setBounds( 50, 30, 30, 30);

  ls0.add("1"); ls0.add("2"); ls0.add("3");
  ls0.add("4"); ls0.add("5"); ls0.add("6");
  ls0.add("7"); ls0.add("8"); ls0.add("9"); ------------(3)
  add(ls0); ls0.setBounds( 10, 30, 30, 160);

  b0.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent evt){
    if(cb0.getState()){          ------------(4)
     t0.setText(ls0.getSelectedItem() + "年連続" + 
     ch0.getSelectedItem() + "回目の出場");
     l0.setText(ls0.getSelectedItem() + "年連続" + 
     ch0.getSelectedItem() + "回目の出場");
     ta0.setText(ls0.getSelectedItem() + "年連続" + 
     ch0.getSelectedItem() + "回目の出場");
    } else {
     t0.setText(ls0.getSelectedItem() + "年ぶり" +
     ch0.getSelectedItem() + "回目の出場");
     l0.setText(ls0.getSelectedItem() + "年ぶり" + 
     ch0.getSelectedItem() + "回目の出場");
     ta0.setText(ls0.getSelectedItem() + "年ぶり" + 
     ch0.getSelectedItem() + "回目の出場");
    }
   }
  }); 
 }

 public static void main(String argv[]){
  Frame win = new GUId();
  win.setSize(400, 320);
  win.setVisible(true);
 }
}

実行結果
 

考察
(1)これまでに出てきたGUI部品、Button,TextField,Label,TextArea,Checkbox,Choice,Listクラスの
  インスタンスを作り、それぞれに代入している。


(2)Choiceコンポーネントに1から6までの数字を格納している。


(3)Listコンポーネントに1から9までの数字を格納している。


(4)getState()メソッドを使い、cb0がチェックされているかどうかで処理を分岐させている。
   チェックされていれば〜年連続〜回目の出場、チェックされていなければ〜年ぶり〜回目の出場と表示される。
  getSelectedItem()メソッドを使い、年数にはls0で、回数にはch0で選択された項目がそれぞれ代入される。

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

ソースプログラム
import java.awt.*;
import java.awt.event.*;

public class ondo extends Frame {
    Button    b0 = new Button("C to F");
    Button    b1 = new Button("F to C");
    Label     x0 = new Label("温度換算器");
    Label     x1 = new Label("換算結果→");

    TextField t0 = new TextField();
    TextField t1 = new TextField();

        public ondo() {
        setLayout(null);
        add(t0); t0.setBounds(10, 40, 80, 30);
        add(t1); t1.setBounds(100, 120, 80, 30);
        add(b0); b0.setBounds(100,  40, 80, 30);
        add(b1); b1.setBounds(100, 80, 80, 30);
        
        add(x0); x0.setBounds(50, 20, 180, 30);
        add(x1); x1.setBounds(10, 130, 180, 30);
        
        b0.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
               try{
                int i = (new Integer(t0.getText())).intValue();
                  t1.setText("" + (i*1.8+32));
               }catch(Exception ex) {
                 t1.setText("error");
               }
            }
           });

           b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
               try{
                int i = (new Integer(t0.getText())).intValue();
                  t1.setText("" + (i-32)/1.8);
               }catch(Exception ex) {
                   t1.setText("error");
               }
            }
          });
        }
  
    public static void main(String[] args) {
        Frame win = new ondo();
        win.setSize(200, 160);
        win.setVisible(true);
        win.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent evt){
                System.exit(0);
         }
       });
    }
}

実行結果
  

考察
摂氏:℃ 華氏:F 摂氏と華氏の関係 ℃=(F−32)/1.8 F=32+℃×1.8
getSelectedItem()メソッドを使いChoiceで選択された項目で処理を分岐させている。 摂氏から華氏への変換式は 華氏 = 摂氏 × 1.8 + 32 なので ChoiceでC to Fが選択された場合は i = (int)(i * 1.8f + 32)と処理する。 (int)は数字を分かりやすくするために整数型に変換するために記述した。 また、F to Cが選択されていた場合は逆に i = (int)((i - 32) / 1.8f)となる。

5.「電卓」プログラム。中身は自分の思うように。

ソースプログラム
import java.awt.*;
import java.awt.event.*;

public class Dentaku extends Frame {
   int l1,l2;
   Button b0  = new Button("0");
   Button b1  = new Button("1");
   Button b2  = new Button("2");
   Button b3  = new Button("3");
   Button b4  = new Button("4");
   Button b5  = new Button("5");
   Button b6  = new Button("6");
   Button b7  = new Button("7");
   Button b8  = new Button("8");
   Button b9  = new Button("9");
   Button ba  = new Button("+");
   Button bb  = new Button("-");
   Button bc  = new Button("*");
   Button bd  = new Button("/");
   Button be  = new Button("=");
   Button bf  = new Button("C");
   Button bg  = new Button("AC");
   TextField t0 = new TextField("0");

   public Dentaku() {
        setLayout(null);
        add(t0); t0.setBounds(10,  50,  230, 40);
        add(b0); b0.setBounds(10,  230, 120, 34);
        add(b1); b1.setBounds(10,  200, 60,  34);
        add(b2); b2.setBounds(68,  200, 60,  34);
        add(b3); b3.setBounds(126, 200, 60,  34);
        add(b4); b4.setBounds(10,  170, 60,  34);
        add(b5); b5.setBounds(68,  170, 60,  34);
        add(b6); b6.setBounds(126, 170, 60,  34);
        add(b7); b7.setBounds(10,  140, 60,  34);
        add(b8); b8.setBounds(68,  140, 60,  34);
        add(b9); b9.setBounds(126, 140, 60,  34);
        add(ba); ba.setBounds(184, 170, 60,  34);
        add(bb); bb.setBounds(184, 140, 60,  34);
        add(bc); bc.setBounds(126, 110, 60,  34);
        add(bd); bd.setBounds(68,  110, 60,  34);
        add(be); be.setBounds(184, 200, 60,  64);
        add(bf); bf.setBounds(10, 110, 60,  34);
        add(bg); bg.setBounds(184,  110, 60,  34);

        ba.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                l1 =(new Integer(t0.getText())).intValue();
                t0.setText("0");
                l2=0;
                }
        });
        bb.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                 l1 =(new Integer(t0.getText())).intValue();
                t0.setText("0");
                l2=1;
            }
        });
        bc.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                 l1 =(new Integer(t0.getText())).intValue();
                t0.setText("0");
                l2=2;
            }
        });
        bd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                 l1 =(new Integer(t0.getText())).intValue();
                t0.setText("0");
                l2=3;
            }
        });

        be.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                int i =(new Integer(t0.getText())).intValue();----(1)
                if(l2 == 0){                   //-----------------(2)
                    int sum =( l1 + i);
                    t0.setText(""+sum);

                }
                else if(l2 == 1){
                    int sum = l1 - i;
                    t0.setText(""+sum);
                }
                else if(l2 == 2){
                    int sum = l1 * i;
                    t0.setText(""+sum);
                }
                else if(l2 == 3){
                    int sum = l1 / i;
                    t0.setText(""+sum);
                }
                else {
                           int sum=l1;
                    t0.setText(""+sum);
                }
            }
        });
        bf.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                int l1=Integer.parseInt(t0.getText());
                t0.setText("0");
                l2=5;          //---------------------------(3)
            }
        });
        bg.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                t0.setText("0");
            }
        });
        b0.addActionListener(new ActionListener() {
            public void actionP

実行結果


考察
(1)Integer.parseInt(t0.getText()); // t0.getText()の数値を変換してint型で返す

(2)t0.getTextが指す数値、つまり後から押された数値(現在表示されている数値)をint iで返す。
   もし、l2=a、つまり”+”を押した時なら、
   l1とiの合計をint型のsumとし、
   sumを文字列表現に直して、入力欄に表示させる。

(3)elseを発生させるために5を使った。
   これで、入力欄は0となる。

(4)現在、入力欄にある数値を10倍して押されたボタンの数値を加算させる。
   この操作を行わないで実行すると、2桁以上の数値が表示できない。

(5)現在のオブジェクトの値の文字列表現を返す。

感想


参考文献




もどる