アプリ版:「スタンプのみでお礼する」機能のリリースについて

足し算を行うだけのプログラムを組むことができたのですが、
四則演算を行いたいと考えています。
下記のようなプログラムでは、ボタンが=のボタンなのですが、
そのボタンを+,-,*,/の4つにおきかえて、各ボタンを押したときに
各ボタンの処理を行うのはどのようにすればいいのでしょうか?
分かる方、ご教授よろしくおねがいします。
import java.applet.Applet;
import java.awt.*; // java.awtパッケージのインポート
import java.awt.event.*;

public class SampleD10L2 extends Applet {

private Button btn_culc; // +ボタン
private TextField txt_A, txt_B, txt_answer; // 数値入力用テキストボックス
public void init() {
// ボタンのインスタンスを作成
btn_culc = new Button("=");
// ボタンのイベント処理を定義
btn_culc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// txt_Aに入力された値 + txt_Bに入力された値を計算
int intAnswer = Integer.parseInt(txt_A.getText()) + Integer.parseInt(txt_B.getText());
// 答えをtxt_answerに表示
txt_answer.setText(Integer.toString(intAnswer));
}
});

// コンポーネントの初期化
txt_A = new TextField("0", 3);
txt_B = new TextField("0", 3);
lbl_plus = new Label(" + ");
txt_answer = new TextField("0", 5);

// コンポーネントを追加
this.add(txt_A); // 自分自身のaddメソッドを呼び出す(this.は省略可能)
this.add(lbl_plus);
this.add(txt_B);
this.add(btn_culc);
this.add(txt_answer);
}
}

A 回答 (2件)

足し算ができたのだからほかの演算も同じことをすればいいだけです。



1.
private Button btn_culc; // +ボタン

↑を四則演算分追加する。
private Button btn_minus; // -ボタン
private Button btn_multi; // *ボタン
private Button btn_div; // /ボタン

2.
btn_culc = new Button("=");
// ボタンのイベント処理を定義
btn_culc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// txt_Aに入力された値 + txt_Bに入力された値を計算
int intAnswer = Integer.parseInt(txt_A.getText()) + Integer.parseInt(txt_B.getText());
// 答えをtxt_answerに表示
txt_answer.setText(Integer.toString(intAnswer));
}
});

init内の↑処理を追加したボタン分追加し、足し算の部分を書き換える。

btn_minus= new Button("-");
// ボタンのイベント処理を定義
btn_culc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// txt_Aに入力された値 - txt_Bに入力された値を計算
int intAnswer = Integer.parseInt(txt_A.getText()) - Integer.parseInt(txt_B.getText());
// 答えをtxt_answerに表示
txt_answer.setText(Integer.toString(intAnswer));
}
});

(*と/の処理も同じように追加すること。)

3.
this.add(btn_culc);

追加したボタンの数だけaddする。
this.add(btn_minus);
this.add(btn_multi);
this.add(btn_div);

これだけです。
    • good
    • 1
この回答へのお礼

btn_minus= new Button("-");
// ボタンのイベント処理を定義
btn_culc.addActionListener(new ActionListener() {
↑部分のところは
btn_minus.addActionListener(new ActionListener() {
という風にしなくてもいけるんですか?

お礼日時:2009/01/19 18:12

コピペ時に直し忘れてましたね。


そのように直してください。
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!