6

Eclipse を使用して電卓を作成していますが、ユーザーが 2 つの値を入力する必要があるため、問題が発生しています。これが実行クラスのコードです。

import display.Gui;

public class Main {

public static void main(String argsp[]) {

    Gui window = new Gui();
    double a = 0, b = 0, c = 0;
    String operator;
    boolean calculate = true;

    window.setVisible(true);
    window.setSize(500, 400);
    window.setResizable(false);
    window.setLocationRelativeTo(null);

    while (calculate) {
        window.textArea_1.append("Enter an equation.\n");
        a = Double.parseDouble(window.textField.getText());
        operator = window.textField.getText();
        b = Double.parseDouble(window.textField.getText());

        if (operator.contains("+"))
            c = a + b;

        if (operator.contains("-"))
            c = a - b;

        if (operator.contains("*"))
            c = a * b;

        if (operator.contains("/"))
            c = a / b;

        if (operator.contains("x^2"))
            c = a * a;

        if (operator.contains("sqrt"))
            c = Math.sqrt(a);

        if (operator.contains("%"))
            c = a / 100;

        window.textArea.append("" + c + "\n");
        window.textArea.append("");
        window.textArea.append("Would you like to make another calculation? [Yes/No]\n");

        String calculation = window.textField.getText();

        try {
        if (calculation.equalsIgnoreCase("Yes"))
            calculate = true;

        if (calculation.equalsIgnoreCase("No"))
            calculate = false;
        } catch (Exception e) {
            window.textArea_1.append("Please enter yes or no");
        }

    }
}

}

JFrameのクラスは次のとおりです。

import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Gui extends JFrame {

public JTextArea textArea, textArea_1;
public JTextField textField;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Gui frame = new Gui();
                frame.setVisible(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Gui() {
    setBounds(100, 100, 450, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().setLayout(new BorderLayout(0, 0));

    textField = new JTextField();
    textField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent Ev) {
            textArea.append(textField.getText() + "\n");
            textField.setText("");
        }
    });
    textField.requestFocus();
    getContentPane().add(textField, BorderLayout.SOUTH);
    textField.setColumns(10);

    textArea = new JTextArea();
    textArea.setEditable(false);
    textArea.setPreferredSize(new Dimension(215, 200));
    getContentPane().add(textArea, BorderLayout.WEST);

    textArea_1 = new JTextArea();
    textArea_1.setEditable(false);
    textArea_1.setPreferredSize(new Dimension(215, 200));
    getContentPane().add(textArea_1, BorderLayout.EAST);

}

使ってみたDouble.parseDouble(window.textField.getText());

しかし、それはうまくいきませんでした。どうすればそれを機能させることができますか?前もって感謝します。

4

4 に答える 4

1

まず第一に、プログラムの設計に問題があると思います。イベント (ボタンのクリック、キーストロークの押下など) を使用して計算をトリガーしないのはなぜですか? このプログラムでは、while ループの利点がわかりません。

また、一部の人々がすでに指摘しているように、コードはユーザー入力の前であっても、テキストフィールドから値を読み取って解析しています。それは確かに無効な結果をもたらします。

次のようなものを試してください(テストされていません):

calcButton = new JButton("Calculate");
calcButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent Ev) {
        actionCalc();
    }
});


public void actionCalc(){
    // get the string
    // validate string (check for empty string etc)
    // parse to Double
    Double val = Double.parseDouble(window.textField.getText());
    ...
}
于 2012-09-17T02:12:15.113 に答える
0

テキストがそこにあるかどうかを実際にチェックせずに、TextFieldからテキストを要求しています。このようにループしたい場合は、最初にテキストが入力されているかどうかを確認してから、入力をdoubleに割り当てる必要があります。ただし、別の戦略をお勧めします。

ここでループを使用するというあなたの論理は、私の意見では最善ではありません。TextFieldから両方の数値を読み取る必要がある場合は、実際にKeyListenerを追加して、Enterキーを待ちます。何かのようなもの

擬似コード

...
// global vals
double a = Null;
double b = Null;
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
        if (!window.textField.getText().equals("")) {
            // check if input is a legal double value
            // notify user that you recieved the first number
            // and request the next input.
            // once both inputs have been entered do your calculation and 
            // output the result. The program will continue to respond to key triggers.
        }
    }
}

便利なリンク

KeyListenersに関する詳細情報は次のとおりです。http: //docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

TextFieldのリンクとその使用方法は次のとおりです。http: //docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

于 2012-09-17T03:17:53.863 に答える
0

これを行う方法は次のとおりです。

double value=Double.parseDouble(jtextfield-name.getText());
于 2014-11-13T12:37:00.943 に答える