簡體   English   中英

字符串加倍,然后再次返回。 (Java)

[英]String to double, then back again. (Java)

我正在嘗試用Java開發一個簡單的稅率計算器程序,但似乎無法正確執行計算。 在代碼中,我最終不得不將JTextField輸入轉換為double變量,然后轉換為字符串。 由於某種原因,這不起作用,並帶來了許多錯誤。 我知道必須有某種更簡單的方式來編寫此代碼,因此任何想法都將不勝感激。

import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.lang.*;


public class TaxCalculator extends JFrame {

    String twelve;
    JTextField input;
    JLabel ans;

    public TaxCalculator() {
        JFrame frame = new JFrame("Tax Calculator");
        JTextField input = new JTextField(10);
        JLabel ans = new JLabel("");
        JButton twelve = new JButton("12%");

        frame.setVisible(true);
        frame.setLayout(new FlowLayout());
        frame.setSize(250, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new JLabel("Price of Item:"));
        frame.add(input);
        frame.add(ans);
        frame.add(twelve);

        twelve.addActionListener(new HandlerClass());

    }

    public static void main(String[] args) {
        TaxCalculator calc = new TaxCalculator();
    }

    public class HandlerClass implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
            double fnum = Double.parseDouble(input.getText());

            if (ae.getSource() == twelve) {
                fnum = (fnum / 0.12) + fnum;
                ans.setText(Double.toString(fnum));
            }

        }

    }
}

問題是您已經聲明了JTextField input; 作為類變量,但還創建了一個同名的局部變量,並將其添加到您的JFrame中。 這就是為什么在執行double fnum = Double.parseDouble(input.getText());時遇到NullPointerException原因double fnum = Double.parseDouble(input.getText());

暫無
暫無

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

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