簡體   English   中英

如何從TextField獲取用戶輸入並將其轉換為Double?

[英]How Do I Get User Input from a TextField and Convert it to a Double?

我正在使用Eclipse構建計算器而我遇到了麻煩,因為我需要輸入2個值。 這是我的run類的代碼。

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());

但那沒用。 我怎樣才能使它工作? 提前致謝。

首先,我認為您的程序設計存在一些問題。為什么不使用事件(按鈕點擊,按鍵擊鍵等)來觸發計算? 我沒有看到這個程序中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());
    ...
}

您正在從TextField請求文本而不實際檢查文本是否存在。 如果您想以這種方式循環,則必須首先查看是否輸入了文本,然后將輸入分配給double。 我會推薦一個不同的策略。

在我看來,你在這里使用循環的邏輯並不是最好的。 如果你必須從TextField中讀取這兩個數字,我實際上會添加一個KeyListener並等待輸入鍵。 就像是

偽代碼

...
// 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

這是你如何做到的:

double value=Double.parseDouble(jtextfield-name.getText());

你可以直接使用:

Double.valueOf("Pass your string here");

它是一個靜態方法,返回參數中給出的任何內容的double值。

暫無
暫無

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

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