2012-07-20 3 views
0

나는 자바로 간단한 세금 계산 프로그램을 만들려고 노력하고 있으며, 계산이 올바르게 작동하는 것 같지 않습니다. 코드에서 JTextField 입력을 이중 변수로 변환 한 다음 문자열로 변환해야했습니다. 웬일인지, 이것은 작동하지 않고 많은 실수를 야기한다. 나는 이것을 작성하는 더 간단한 방법이 있어야한다는 것을 알고 있으므로, 어떤 아이디어라도 감사 할 것입니다.문자열을 이중으로 한 다음 다시 되돌립니다. (자바)

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

     } 

    } 
} 
+3

어떤 에러가 나나요? 이 오류의 전체 스택 추적은 무엇입니까? – Jeffrey

+0

ur 계산에는 문제가 없습니다. 문제는 변수의 재 선언에 있습니다. – Davuth

답변

7

문제는 당신은 클래스 변수로 JTextField input;를 선언뿐만 아니라 같은 이름의 지역 변수를 생성하고 JFrame의에 추가됩니다. 그래서 NullPointerException을 만날 때 double fnum = Double.parseDouble(input.getText());

+1

@ SPARK 같은 대답은'answer'과'12' 필드에 있습니다. 또한'twelve'의 경우 타입을'String'에서'JButton'으로 변경해야합니다. 그렇지 않으면'ae.getSource() == twelve'는 무의미합니다. – Pshemo

+0

고마워, 지금 일했다. – SPARK

+0

확실, 도움이 되니 기쁩니다 :) – Sujay

관련 문제