電卓


8進, 10進, 16進の電卓

// Ensyu2.java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.math.*;
import javax.swing.*;

/**
 * <applet code="Ensyu2.class" width="500" height="500"></applet>
 */ 
public class Ensyu2 extends JApplet implements ActionListener {
    int status; // 0: init, 1: first operator 2: +-x/, 3: second operator 4: =
    JTextField field;
    JRadioButton oct, dec, hex;
    JRadioButton prev;
    JButton[] ns;
    JButton[] ls;
    JButton pls, mns, mul, div;
    JButton ac, c;
    JButton equal;
    JButton dpoint;
    String chars;
    String operators = "+-x/";
    char ope = '?';
    String cur;
    JTextField debug;

    void debug() {
        this.debug.setText("status: " + status + ", ope: " + ope + ", cur: " + cur);
    }

    public Ensyu2() {
        Font font  = new Font("Monospaced", Font.PLAIN, 14);
        this.setLayout(new BorderLayout());
        this.field = new JTextField();
        this.field.setEditable(false);
        this.field.setHorizontalAlignment(JTextField.RIGHT);
        this.chars = "0123456789.+-x/=LZ";
        this.oct = new JRadioButton("Octal");         oct.setMnemonic(KeyEvent.VK_O); oct.addActionListener(this);
        this.dec = new JRadioButton("Decimal", true); dec.setMnemonic(KeyEvent.VK_D); dec.addActionListener(this);
        this.hex = new JRadioButton("Hexadecimal");   hex.setMnemonic(KeyEvent.VK_H); hex.addActionListener(this);
        ButtonGroup bg = new ButtonGroup();
        bg.add(oct);
        bg.add(dec);
        bg.add(hex);
        this.prev = dec;
        JPanel ccp = new JPanel(new BorderLayout());
        JPanel np = new JPanel();
        np.add(oct);
        np.add(dec);
        np.add(hex);
        ccp.add(np, BorderLayout.NORTH);
        this.ns = new JButton[10];
        for(int i=0; i<10; i++) {
            this.ns[i] = new JButton("" + i);
            this.ns[i].addActionListener(this);
            this.ns[i].setFont(font);
        }
        this.ls = new JButton[6];
        for(int i=0; i<6; i++) {
            this.ls[i] = new JButton("" + (char)('A' + i));
            this.ls[i].addActionListener(this);
            this.ls[i].setFont(font);
            this.ls[i].setEnabled(false);
        }
        this.pls = new JButton("+"); this.pls.setFont(font); this.pls.addActionListener(this);
        this.mns = new JButton("-"); this.mns.setFont(font); this.mns.addActionListener(this);
        this.mul = new JButton("x"); this.mul.setFont(font); this.mul.addActionListener(this);
        this.div = new JButton("/"); this.div.setFont(font); this.div.addActionListener(this);
        this.ac  = new JButton("AC"); this.ac.setFont(font); this.ac.addActionListener(this);
        this.c   = new JButton("CL"); this.c.setFont(font); this.c.addActionListener(this);
        this.equal = new JButton("="); this.equal.setFont(font); this.equal.addActionListener(this);
        this.dpoint = new JButton("."); this.dpoint.setFont(font); this.dpoint.addActionListener(this);
        JPanel cp = new JPanel();
        GridBagLayout layout = new GridBagLayout();
        cp.setLayout(layout);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ls[0], gbc); cp.add(this.ls[0]);
        gbc.gridx = 1; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ls[1], gbc); cp.add(this.ls[1]);
        gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ls[2], gbc); cp.add(this.ls[2]);
        gbc.gridx = 3; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ls[3], gbc); cp.add(this.ls[3]);
        gbc.gridx = 4; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ls[4], gbc); cp.add(this.ls[4]);
        gbc.gridx = 5; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ls[5], gbc); cp.add(this.ls[5]);
        gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[7], gbc); cp.add(this.ns[7]);
        gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[8], gbc); cp.add(this.ns[8]);
        gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[9], gbc); cp.add(this.ns[9]);
        gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(div, gbc); cp.add(div);
        gbc.gridx = 5; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(ac, gbc); cp.add(ac);
        gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[4], gbc); cp.add(this.ns[4]);
        gbc.gridx = 2; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[5], gbc); cp.add(this.ns[5]);
        gbc.gridx = 3; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[6], gbc); cp.add(this.ns[6]);
        gbc.gridx = 4; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(mul, gbc); cp.add(mul);
        gbc.gridx = 5; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(c, gbc); cp.add(c);
        gbc.gridx = 1; gbc.gridy = 3; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[1], gbc); cp.add(this.ns[1]);
        gbc.gridx = 2; gbc.gridy = 3; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[2], gbc); cp.add(this.ns[2]);
        gbc.gridx = 3; gbc.gridy = 3; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[3], gbc); cp.add(this.ns[3]);
        gbc.gridx = 4; gbc.gridy = 3; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(mns, gbc); cp.add(mns);
        gbc.gridx = 5; gbc.gridy = 3; gbc.gridwidth = 1; gbc.gridheight = 2; layout.setConstraints(equal, gbc); cp.add(equal);
        gbc.gridx = 1; gbc.gridy = 4; gbc.gridwidth = 2; gbc.gridheight = 1; layout.setConstraints(this.ns[0], gbc); cp.add(this.ns[0]);
        gbc.gridx = 3; gbc.gridy = 4; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(dpoint, gbc); cp.add(dpoint);
        gbc.gridx = 4; gbc.gridy = 4; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(pls, gbc); cp.add(pls);
        ccp.add(cp, BorderLayout.CENTER);
        this.debug = new JTextField();
        this.debug.setEditable(false);
        this.debug.setHorizontalAlignment(JTextField.RIGHT);
        this.add(field, BorderLayout.NORTH);
        this.add(ccp, BorderLayout.CENTER);
        this.add(debug, BorderLayout.SOUTH);
        setFocusable(true);
        requestFocus();
        addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                handleKeyEvent(e);
            }
        });
        reset();
    }

    private void reset() {
        this.field.setText("0");
        this.status = 0;
        this.cur = null;
        this.ope = '?';
        debug();
    }

    private void alert(String msg) { JOptionPane.showMessageDialog(this, msg); }

    private boolean show(char ope, String cur) {
        if(getNum(prev) == 10) {
            BigDecimal cur0 = new BigDecimal(cur);
            BigDecimal cur1 = new BigDecimal(field.getText());
            boolean succeed = true;
            switch(ope) {
                case '+': { field.setText(cur0.add(cur1).toString()); break; }
                case '-': { field.setText(cur0.subtract(cur1).toString()); break; }
                case 'x': { field.setText(cur0.multiply(cur1).toString()); break; }
                case '/':
                          try {
                              field.setText(cur0.divide(cur1).toString());
                          } catch(ArithmeticException aex0) {
                              try {
                                  field.setText(cur0.divide(cur1, 12, BigDecimal.ROUND_HALF_UP).toString());
                              } catch(ArithmeticException aex1) {
                                  alert(aex1.getMessage());
                                  succeed = false;
                              }
                          }
                          break;
                default: { alert("Unexpected exception(invalid operator) ope: " + ope); break; }
            }
            return succeed;
        } else {
            BigInteger cur0 = new BigInteger(cur, getNum(prev));
            BigInteger cur1 = new BigInteger(field.getText(), getNum(prev));
            boolean succeed = true;
            switch(ope) {
                case '+': { field.setText(cur0.add(cur1).toString(getNum(prev)).toUpperCase()); break; }
                case '-': { field.setText(cur0.subtract(cur1).toString(getNum(prev)).toUpperCase()); break; }
                case 'x': { field.setText(cur0.multiply(cur1).toString(getNum(prev)).toUpperCase()); break; }
                case '/':
                          try {
                              field.setText(cur0.divide(cur1).toString(getNum(prev)).toUpperCase());
                          } catch(ArithmeticException aex0) {
                              alert(aex0.getMessage());
                              succeed = false;
                          }
                          break;
                default: { alert("Unexpected exception(invalid operator) ope: " + ope); break; }
            }
            return succeed;
        }
    }

    private void handleInput(char input) throws Exception {
        if(input == 'Z') { reset(); return; }
        boolean isCL = false;
        boolean isFirst = false;
        if(('0' <= input && input <= '9') || ('A' <= input && input <= 'F')) {
            if(status == 0 || status == 2) { status++; isFirst = true; }
            else if(status == 4) { status = 1; isFirst = true; }
            else { /* nop */ }  // status == 1, 3
        } else {
            switch(status) {
                case 0:
                    if(operators.indexOf(input) >= 0) { ope = input; status = 2; }
                    else if(input == 'L') { isCL = true; }
                    else if(input == '.') { isFirst = true; status = 1; }
                    else { return; }    // =
                    break;
                case 1:
                    if(operators.indexOf(input) >= 0) { ope = input; status = 2; }
                    else if(input == 'L') { isCL = true; }
                    else if(input == '.') { /* nop */ }
                    else { return; }    // =
                    break;
                case 2:
                    if(operators.indexOf(input) >= 0) { ope = input; }
                    else if(input == '.') { isFirst = true; status = 3; }
                    else { return; }    // =CL
                    break;
                case 3:
                    if(operators.indexOf(input) >= 0) {
                        if(show(ope, cur)) {
                            ope = input;
                            status = 2;
                        }
                        else { reset(); }
                    }
                    else if(input == 'L') { isCL = true; }
                    else if(input == '=') { status = 4; }
                    else { /* nop */ }  // .
                    break;
                case 4:
                    if(operators.indexOf(input) >= 0) {
                        ope = input;
                        status = 2;
                    }
                    else { return; }    // .=CL
                    break;
            }
        }
        String get = field.getText();
        switch(status) {
            case 0:
                reset();
                break;
            case 1:
            case 3:
                if(isCL) { field.setText("0"); }
                else if(get.equals("0") && input != '.') { field.setText(""+input); }
                else {
                    if(isFirst) { field.setText(input == '.' ? "0." : ""+input); }
                    else if(get.contains(".")) {
                        if(input != '.') { field.setText(get+input); }
                    } else {    // !get.contains(".")
                        field.setText(get+input);
                    }
                }
                break;
            case 2:
                ope = input;
                cur = get;
                break;
            case 4:
                if(show(ope, cur)) {
                    ope = '?';
                    cur = null;
                }
                else { reset(); }
            default:
                break;
        }
        debug();
    }

    // Esc: AC(Z)
    // a,b,c,d,e,f,A,B,C,D,E,F: A,B,C,D,E,F
    // l: CL(L);
    private void handleKeyEvent(KeyEvent e) {
        if(e.isAltDown()) { return; }
        char ch = e.getKeyChar();
        if('a' <= ch && ch <= 'z') { ch += ('A' - 'a'); }
        if(e.getKeyCode() == KeyEvent.VK_ENTER) { ch = '='; }
        else if(e.getKeyCode() == KeyEvent.VK_ESCAPE) { ch = 'Z'; }
        else if(e.getKeyCode() == KeyEvent.VK_PERIOD) { ch = '.'; }
        else if(e.getKeyChar() == '*') { ch = 'x'; }
        else if(ch == 'X') { ch = 'x'; }
        try {
            if(chars.indexOf(ch) == -1) { return; }
            handleInput(ch);
        } catch (Exception exception) {
            alert("Unexpected exception: " + exception.getMessage());
        }
    }
    
    private int getNum(JRadioButton btn) {
        if(btn == oct) { return 8; }
        if(btn == dec) { return 10; }
        if(btn == hex) { return 16; }
        return 0;
    }
    
    private int getNum(char mne) {
        if(mne == 'O') { return 8; }
        if(mne == 'D') { return 10; }
        if(mne == 'H') { return 16; }
        return 0;
    }

    private void setButtonEnabled(char mne) {
        String ftxt = this.field.getText().toLowerCase();
        int pnum = getNum(prev);
        int cnum = getNum(mne);
        if(pnum == cnum) { return; }
        switch(mne) {
            case 'O':
                this.dpoint.setEnabled(false);
                this.ns[8].setEnabled(false);
                this.ns[9].setEnabled(false);
                for(int i=0; i<6; i++) {
                    this.ls[i].setEnabled(false);
                }
                if(pnum == 10) {
                    int idx = ftxt.indexOf('.');
                    String str = idx == -1 ? ftxt : ftxt.substring(0, idx);
                    this.field.setText(new BigInteger(str).toString(8));
                    if(cur != null) {
                        idx = cur.indexOf('.');
                        cur = new BigInteger(idx == -1 ? cur : cur.substring(0, idx)).toString(8);
                    }
                } else {
                    this.field.setText(new BigInteger(ftxt, 16).toString(8));
                    if(cur != null) { cur = new BigInteger(cur, 16).toString(8); }
                }
                this.chars = "01234567+-x/=LZ";
                this.prev = oct;
                break;
            case 'D':
                this.dpoint.setEnabled(true);
                this.ns[8].setEnabled(true);
                this.ns[9].setEnabled(true);
                for(int i=0; i<6; i++) {
                    this.ls[i].setEnabled(false);
                }
                this.field.setText(new BigInteger(ftxt, pnum).toString());
                if(cur != null) { cur = new BigInteger(cur, pnum).toString(); }
                this.chars = "0123456789.+-x/=LZ";
                this.prev = dec;
                break;
            case 'H':
                this.dpoint.setEnabled(false);
                this.ns[8].setEnabled(true);
                this.ns[9].setEnabled(true);
                for(int i=0; i<6; i++) {
                    this.ls[i].setEnabled(true);
                }
                if(pnum == 10) {
                    int idx = ftxt.indexOf('.');
                    String str = idx == -1 ? ftxt : ftxt.substring(0, idx);
                    this.field.setText(new BigInteger(str).toString(16).toUpperCase());
                    if(cur != null) {
                        idx = cur.indexOf('.');
                        cur = new BigInteger(idx == -1 ? cur : cur.substring(0, idx)).toString(16).toUpperCase();
                    }
                } else {
                    this.field.setText(new BigInteger(ftxt, 8).toString(16).toUpperCase());
                    if(cur != null) { cur = new BigInteger(cur, 8).toString(16).toUpperCase(); }
                }
                this.chars = "0123456789+-x/=ABCDEFLZ";
                this.prev = hex;
                break;
                
        }
        debug();
    }
    
    @Override public void actionPerformed(ActionEvent ae) {
        try {
            Object source = ae.getSource();
            if(source instanceof JButton) {
                JButton btn = (JButton)source;
                char input = '\u0000';
                String str = btn.getText();
                if(str.equals("AC")) { input = 'Z'; }
                else if(str.equals("CL")) { input = 'L'; }
                else { input = str.charAt(0); }
                handleInput(input);
            } else if(source instanceof JRadioButton) {
                JRadioButton btn = (JRadioButton)source;
                setButtonEnabled((char)btn.getMnemonic());
            }
            requestFocus();
        } catch(Exception exception) {
            alert("Unexpected exception: " + exception.getClass() + "\n" +  exception.getMessage());
            exception.printStackTrace();
        }
    }
}

電卓

Applet+Swingの電卓です。ページ下方にJavaアプリケーションとして動作させるためのパッチがあります。

// Calculator.java
import java.awt.*;
import java.awt.event.*;
import java.math.*;
import javax.swing.*;

/**
 * <applet code="Calculator.class" width="300" height="300"></applet>
 */ 
public class Calculator extends JApplet implements ActionListener {
    int status; // 0: init, 1: first operator 2: +-x/, 3: second operator 4: =
    JTextField field;
    JButton[] ns;
    JButton pls, mns, mul, div;
    JButton ac, c;
    JButton equal;
    JButton dpoint;
    String operators = "+-x/";
    String chars = "0123456789.+-x/=AC";
    char ope = '?';
    String cur;
    JTextField debug;

    void debug() {
        this.debug.setText("status: " + status + ", ope: " + ope + ", cur: " + cur);
    }

    public Calculator() {
        Font font  = new Font("Monospaced", Font.PLAIN, 14);
        this.setLayout(new BorderLayout());
        this.field = new JTextField();
        this.field.setEditable(false);
        this.field.setHorizontalAlignment(JTextField.RIGHT);
        this.ns = new JButton[10];
        for(int i=0; i<10; i++) {
            this.ns[i] = new JButton("" + i);
            this.ns[i].addActionListener(this);
            this.ns[i].setFont(font);
        }
        this.pls = new JButton("+"); this.pls.setFont(font); this.pls.addActionListener(this);
        this.mns = new JButton("-"); this.mns.setFont(font); this.mns.addActionListener(this);
        this.mul = new JButton("x"); this.mul.setFont(font); this.mul.addActionListener(this);
        this.div = new JButton("/"); this.div.setFont(font); this.div.addActionListener(this);
        this.ac  = new JButton("AC"); this.ac.setFont(font); this.ac.addActionListener(this);
        this.c   = new JButton("C"); this.c.setFont(font); this.c.addActionListener(this);
        this.equal = new JButton("="); this.equal.setFont(font); this.equal.addActionListener(this);
        this.dpoint = new JButton("."); this.dpoint.setFont(font); this.dpoint.addActionListener(this);
        JPanel cp = new JPanel();
        GridBagLayout layout = new GridBagLayout();
        cp.setLayout(layout);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[7], gbc); cp.add(this.ns[7]);
        gbc.gridx = 1; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[8], gbc); cp.add(this.ns[8]);
        gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[9], gbc); cp.add(this.ns[9]);
        gbc.gridx = 3; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(div, gbc); cp.add(div);
        gbc.gridx = 4; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(ac, gbc); cp.add(ac);
        gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[4], gbc); cp.add(this.ns[4]);
        gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[5], gbc); cp.add(this.ns[5]);
        gbc.gridx = 2; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[6], gbc); cp.add(this.ns[6]);
        gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(mul, gbc); cp.add(mul);
        gbc.gridx = 4; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(c, gbc); cp.add(c);
        gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[1], gbc); cp.add(this.ns[1]);
        gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[2], gbc); cp.add(this.ns[2]);
        gbc.gridx = 2; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(this.ns[3], gbc); cp.add(this.ns[3]);
        gbc.gridx = 3; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(mns, gbc); cp.add(mns);
        gbc.gridx = 4; gbc.gridy = 2; gbc.gridwidth = 1; gbc.gridheight = 2; layout.setConstraints(equal, gbc); cp.add(equal);
        gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2; gbc.gridheight = 1; layout.setConstraints(this.ns[0], gbc); cp.add(this.ns[0]);
        gbc.gridx = 2; gbc.gridy = 3; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(dpoint, gbc); cp.add(dpoint);
        gbc.gridx = 3; gbc.gridy = 3; gbc.gridwidth = 1; gbc.gridheight = 1; layout.setConstraints(pls, gbc); cp.add(pls);
        this.debug = new JTextField();
        this.debug.setEditable(false);
        this.debug.setHorizontalAlignment(JTextField.RIGHT);
        this.add(field, BorderLayout.NORTH);
        this.add(cp, BorderLayout.CENTER);
        this.add(debug, BorderLayout.SOUTH);
        setFocusable(true);
        requestFocus();
        addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                handleKeyEvent(e);
            }
        });
        reset();
    }

    private void reset() {
        this.field.setText("0");
        this.status = 0;
        this.cur = null;
        this.ope = '?';
        debug();
    }

    private void alert(String msg) { JOptionPane.showMessageDialog(this, msg); }

    private boolean show(char ope, String cur) {
        BigDecimal cur0 = new BigDecimal(cur);
        BigDecimal cur1 = new BigDecimal(field.getText());
        boolean succeed = true;
        switch(ope) {
            case '+': { field.setText(cur0.add(cur1).toString()); break; }
            case '-': { field.setText(cur0.subtract(cur1).toString()); break; }
            case 'x': { field.setText(cur0.multiply(cur1).toString()); break; }
            case '/':
                      try {
                          field.setText(cur0.divide(cur1).toString());
                      } catch(ArithmeticException aex0) {
                          try {
                              field.setText(cur0.divide(cur1, 12, BigDecimal.ROUND_HALF_UP).toString());
                          } catch(ArithmeticException aex1) {
                              alert(aex1.getMessage());
                              succeed = false;
                          }
                      }
                      break;
            default: { alert("Unexpected exception(invalid operator) ope: " + ope); break; }
        }
        return succeed;
    }

    private void handleInput(char input) throws Exception {
        if(input == 'A') { reset(); return; }
        int num = 0;
        boolean isC = false;
        boolean isFirst = false;
        if('0' <= input && input <= '9') {
            num = (int)(input - '0');
            if(status == 0 || status == 2) { status++; isFirst = true; }
            else if(status == 4) { status = 1; isFirst = true; }
            else { /* nop */ }  // status == 1, 3
        } else {
            switch(status) {
                case 0:
                    if(operators.indexOf(input) >= 0) { ope = input; status = 2; }
                    else if(input == 'C') { isC = true; }
                    else if(input == '.') { isFirst = true; status = 1; }
                    else { return; }    // =
                    break;
                case 1:
                    if(operators.indexOf(input) >= 0) { ope = input; status = 2; }
                    else if(input == 'C') { isC = true; }
                    else if(input == '.') { /* nop */ }
                    else { return; }    // =
                    break;
                case 2:
                    if(operators.indexOf(input) >= 0) { ope = input; }
                    else if(input == '.') { isFirst = true; status = 3; }
                    else { return; }    // =C
                    break;
                case 3:
                    if(operators.indexOf(input) >= 0) {
                        if(show(ope, cur)) {
                            ope = input;
                            status = 2;
                        }
                        else { reset(); }
                    }
                    else if(input == 'C') { isC = true; }
                    else if(input == '=') { status = 4; }
                    else { /* nop */ }  // .
                    break;
                case 4:
                    if(operators.indexOf(input) >= 0) {
                        ope = input;
                        status = 2;
                    }
                    else { return; }    // .=C
                    break;
            }
        }
        String get = field.getText();
        switch(status) {
            case 0:
                reset();
                break;
            case 1:
            case 3:
                if(isC) { field.setText("0"); }
                else if(get.equals("0") && input != '.') { field.setText(""+input); }
                else {
                    if(isFirst) { field.setText(input == '.' ? "0." : ""+input); }
                    else if(get.contains(".")) {
                        if(input != '.') { field.setText(get+input); }
                    } else {    // !get.contains(".")
                        field.setText(get+input);
                    }
                }
                break;
            case 2:
                ope = input;
                cur = get;
                break;
            case 4:
                if(show(ope, cur)) {
                    ope = '?';
                    cur = null;
                }
                else { reset(); }
            default:
                break;
        }
        debug();
    }

    private void handleKeyEvent(KeyEvent e) {
        char ch = e.getKeyChar();
        if('a' <= ch && ch <= 'z') { ch += ('A' - 'a'); }
        if(e.getKeyCode() == KeyEvent.VK_ENTER) { ch = '='; }
        else if(e.getKeyCode() == KeyEvent.VK_ESCAPE) { ch = 'A'; }
        else if(e.getKeyCode() == KeyEvent.VK_PERIOD) { ch = '.'; }
        else if(e.getKeyChar() == '*') { ch = 'x'; }
        else if(ch == 'X') { ch = 'x'; }
        try {
            if(chars.indexOf(ch) == -1) { return; }
            handleInput(ch);
        } catch (Exception exception) {
            alert("Unexpected exception: " + exception.getMessage());
        }
    }

    @Override public void actionPerformed(ActionEvent ae) {
        try {
            JButton btn = (JButton)ae.getSource();
            char input = btn.getText().charAt(0);
            handleInput(input);
            requestFocus();
        } catch(Exception exception) {
            alert("Unexpected exception: " + exception.getMessage());
        }
    }
}

Javaアプリケーションとして動作させるためのパッチ

7,10c7
< /**
<  * <applet code="Calculator.class" width="300" height="300"></applet>
<  */ 
< public class Calculator extends JApplet implements ActionListener {
---
> public class Calculator extends JFrame implements ActionListener {
231a229,235
>     
>     public static void main(String[] args) {
>         Calculator self = new Calculator();
>         self.setSize(300, 300);
>         self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
>         self.setVisible(true);
>     }

CONTENTS

最新の20件

2020-11-14 2005-12-06 2006-11-04 2012-07-15 2009-06-19 2011-03-03 2006-12-13 2007-11-05 2014-07-22 2014-07-19 2014-07-09 2014-01-14 2012-09-03 2012-03-28

今日の5件

人気の30件

  • counter: 2100
  • today: 1
  • yesterday: 1
  • online: 1