簡體   English   中英

Java:簡單計算器(數據驗證)

[英]Java: Simple Calculator(data validation)

我完全不熟悉Java和OOP。 我正在嘗試使用Java Swing創建一個簡單的計算器。 如果沒有添加點,我希望用戶在第一個之后不能輸入零​​。 我已經進行了很長時間的集思廣益,但找不到解決方案:(現在,如果僅輸入一個數字(不同於0),則不能輸入0。在其他所有情況下都可以使用。

這是我的代碼的一部分:

    public class Calculator extends JFrame implements ActionListener {

    boolean hasDot = false;
    boolean hasNull = false;

    JButton button0;
    JButton buttonDot;
    JTextArea text;

    public Calculator(){

    //Constructor comes here 
    button0 = new JButton("0");
    buttonDot = new JButton(".");
    text = new JTextArea(1, 20);
    }

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == button0) {

            if (text.getText().length() > 0)
                hasNull = true;

            if (hasNull == false) {
                text.append("0");
                hasNull = true;
            }
            if (hasNull == true && hasDot == true) {
                hasNull = false;
                text.append("0");
            }
            if (text.getText().length() > 1 && hasDot == false)
                text.append("0");
        }

        if (e.getSource() == buttonDot && (hasDot == false)
                && text.getText().length() != 0) {
            text.append(".");
            hasDot = true;
            hasNull = false;
        }
    }
}   

我認為這可以解決問題。 您可能想要避免讓JFrame成為動作偵聽器。 它使代碼更難閱讀。 您還需要實現兩個函數isNextDigitAfterDecimalPointgetButtonNumber ,但它們應該不太難。 這些將使您的代碼更易於推理。

public Calculator() {

    //Constructor comes here 
    button0 = new JButton("0");
    button0.addActionListener(mNumberButtonActionListener);
    // other buttons ...

    buttonDot = new JButton(".");
    buttonDot.addActionListener(mDotButtonActionListener);
    text = new JTextArea(1, 20);
}

private ActionListener mNumberButtonActionListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        int numberToAppend = getButtonNumber(e.getSource());
        if (isNextDigitAfterDecimalPoint()) {
            text.append(Integer.toString(numberToAppend))
        } else {
            String currentNumberText = text.getText()
            if (currentNumberText.size() == 0 || !currentNumberText.get(0).equals("0")) {
                text.append(Integer.toString(numberToAppend));
            }
        }
    }
}

private boolean isNextDigitAfterDecimalPoint() { ... }

private int getButtonNumber(JButton button) { ... }

private ActionListener mDotButtonActionListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (isNextDigitAfterDecimalPoint()) {
            text.append(".");
        }
    }
}

您可能還想考慮的一件事是,您的hasNull和hasDot變量並不是真正必需的。 它們為您的應用程序增加了額外的狀態。 您可以使用解釋文本字段內容的方法來獲得這兩個值。 這樣,您無需記住在文本更改時進行更新。

例如。

boolean hasDot() {
    return text.getText().contains(".");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM