2012-03-01 87 views
0

有4個類別:Main,GUI,LogicCalculator。我很難讓Calculator課程正確,第一個操作/計算給了我錯誤的答案,但下一個是正確的。我試圖爲第一個和第二個數字創建另一個變量(fnumsnum),但它不起作用。我是否需要修改邏輯類?Java計算器GUI操作

主類

class Main 
{ 
    public static void main(String args[]) 
    { 
    GUI gui = new GUI(); 
    gui.display(); 
    } 
} 

GUI類

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

class GUI 
{ 
    private static final int H = 400;  // Height of window pixels 
    private static final int W = 500;  // Width of window pixels 

    private JLabel  theMes  = new JLabel();  // Message area 
    private JTextArea theOutput1 = new JTextArea(); // Input number area 
    private JTextArea theOutput2 = new JTextArea(); // Result area 
    private JScrollPane theSP  = new JScrollPane(); 

    private ButtonPress onButtonPress = new ButtonPress(); 

    public void display() 
    { 
    JFrame rpc   = new JFrame();   // Window 
    Container cp   = rpc.getContentPane(); // Content Pane 
    Container rootWindow = (Container) rpc;   // Root Window 
    cp.setLayout(null);        // No layout manager 
    rootWindow.setSize(W, H);      // Size of Window 

    String labels[] = { 
     "7", "8", "9", "", "CR", "+", 
     "4", "5", "6", "", "=", "-", 
     "1", "2", "3", "", "", "*", 
     "C", "0", "", "", "", "/" }; 

    final int LABELS = labels.length;  // # Button Labels 

    final int GAP = 15;     // Horizontal Gap 

    final int HLAB = 20;     // Label 
    final int SHLAB = GAP; 
    final int EHLAB = SHLAB+HLAB; 

    final int HTA1 = 30;     // Output area 1 
    final int SHTA1 = EHLAB + GAP; 
    final int EHTA1 = SHTA1 + HTA1; 

    final int HTA2 = 100;     // Output area 2 
    final int SHTA2 = EHTA1 + GAP; 
    final int EHTA2 = SHTA2 + HTA2; 

    final int HBUT = 170;     // Buttons 
    final int SHBUT = EHTA2 + GAP; 

    final int BNR = 4, BNC = 6;  // number rows cols of buttons 
    final int BW = W/BNC, BH = HBUT/BNR; // Size of landscape for button 
    final int SBH = SHBUT, SBW = 7;  // Start position for buttons 


    JButton buttons[] = new JButton[LABELS]; 

    Font font = new Font("Serif",Font.BOLD,20);  // Button font 

    for (int i=0; i<LABELS; i++) 
    { 
     if (labels[i].length() >= 1) 
     { 
     buttons[i] = new JButton(labels[i]); 
     final int col = i%BNC * BW, row = i/BNC * BH; 
     buttons[i].setBounds(SBW+col, SBH+row, BW-20, BH-10); 
     buttons[i].addActionListener(onButtonPress); 
     buttons[i].setFont(font); 
     cp.add(buttons[i]); 
     } 
    } 

    font = new Font("Serif",Font.BOLD,14);   // Font is 

    theMes.setBounds(10, SHLAB, W-25, HLAB);  // Message area 
    theMes.setText("");       // Blank 
    theOutput1.setFont(font);     // Uses font 
    cp.add(theMes);        // Add to canvas 

    theOutput1.setBounds(10, SHTA1, W-25, HTA1); // Input Area 
    theOutput1.setText("");      // Blank 
    theOutput1.setFont(font);     // Uses font 
    cp.add(theOutput1);       // Add to canvas 

    font = new Font("Serif",Font.BOLD,14);   // Font is 

    theSP.setBounds(10, SHTA2, W-25, HTA2);  // Scrolling pane 
    theOutput2.setText("");      // Blank 
    theOutput2.setFont(font);     // Uses font 
    cp.add(theSP);        // Add to canvas 
    theSP.getViewport().add(theOutput2);   // In TextArea 
    rootWindow.setVisible(true);     // Make visible 

    theMes.setText("Calculator");    // Opening message 
    } 


    private Calculator calc = new Calculator(); 
    private Logic logic  = new Logic(calc); 

    class ButtonPress implements ActionListener  // Listener 
    { 
    public void actionPerformed(ActionEvent ae) // Interaction 
    { 
     String label = ae.getActionCommand();   // Button label 

     String info = logic.process(label); 

     theOutput2.setText(""); 
     if (info == null) 
     theOutput2.append("" + logic.getResult()); 
     else 
     theOutput2.append(info); 

     theOutput1.setText(""); 
     theOutput1.append("Number entered: " + logic.getNumber()); 
    } 
    } 
} 

邏輯類

class Logic 
{ 
    private enum State { FIRST_NUMBER, SUBSEQUENT_NUMBER }; 
    private State state = State.FIRST_NUMBER; 
    private long number = 0; 
    private char op = ' '; 
    private Calculator calc = null; 


    public Logic(Calculator calculator) 
    { 
    calc = calculator; 
    } 

    public String process(String button) 
    { 
    String info = null; 
    if (button.length() == 1) 
    { 
     char c = button.charAt(0); 
     if (c >= '0' && c <= '9')    // Digit 
     { 
     number = number * 10 + c-'0';   // Build number 
     } else { 
     switch (c) 
     { 
      case 'C' : number = 0; 
        break; 
      case '=' : 
      case '+' : case '-' : 
      case '*' : case '/' : 
      switch (state) 
      { 
       case FIRST_NUMBER: 
       calc.setValue(number); 
       state = State.SUBSEQUENT_NUMBER; 
       break; 
       case SUBSEQUENT_NUMBER: 
       if (op != '=') 
        calc.evaluate(op, number); 
       break; 
      } 
      op = c; number = 0; 
      break; 
     } 
     } 
    } else { 
     if (button.equals("CR"))    // Clear Result 
     { 
     calc.reset(); number = 0; state = State.FIRST_NUMBER; 
     } 
    } 

    return info; 
    } 

    public long getResult() 
    { 
    return calc.getValue(); 
    } 

    public long getNumber() 
    { 
    return number; 
    } 
} 

計算器類

class Calculator 
{ 
//Evaluate an arithmetic operation on the stored result 
// E.g evaluate('+',9) would add 9 to the stored result 
// evaluate('/',3) would divide the stored result 
// by 3 
// actions are '+'. '-', '*', '/' 
//Note: if the operation is 
// evaluate('/',0) the result returned should be 0 


long value; 


public void evaluate(char action, long number) 
{ 

    if (action == '+'){ 
     value += Float.valueOf(number).floatValue(); 


    } 

    else if (action == '-'){ 
     value -= Float.valueOf(number).floatValue(); 

    } 

    else if (action == '*'){ 
     value *= Float.valueOf(number).floatValue(); 

    } 

    else if (action == '/'){ 
     value /= Float.valueOf(number).floatValue(); 

    } 

} 
//Return the stored result 
public long getValue() 
    { 
    return value; 
    } 

//Set the stored result to number 
public void setValue(long number) 
{ 

} 

//Reset the stored number to 0 
public void reset() 
{ 
     if (value != 0) value = 0; 
    } 
} 
+0

'公共靜態浮動的valueOf(String s)將拋出NumberFormatException' – vulkanino 2012-03-01 16:41:04

+0

爲什麼你的setValue()方法沒有任何代碼。它應該有this.value =數字。 – JProgrammer 2012-03-01 16:42:56

回答

3

的問題是,你不實際的setValue方法設置的值:

//Set the stored result to number 
public void setValue(long number) 
{ 
    this.value = number; 
} 

這應該修復它。

+0

是的,這解決了這個問題。 CodeReview +1的 – 2012-03-01 17:00:31

2

因爲答案已經指出,這裏有您的代碼一些一般性的指針:

  1. 你已經按區域,這是很好的破事了。
  2. 您需要在GUI添加rpc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);,否則你的計算器類將contine運行,甚至「退出」圖標已經被關閉。
  3. 此行:Container rootWindow = (Container) rpc;沒有意義,因爲rpc已被引用爲容器。
  4. 你的一些變量名稱是完全神祕的(​​,SHTA1,HTA2?)。始終標註適當和描述性的內容。
  5. 您正在使用long s來存儲和顯示您的值,但float s執行實際的數學。這意味着該程序會生成更奇怪的結果 - 例如,9/2 = 4。另外,反駁您的評論,9/0 = 9223372036854775807。我建議你生成最初的數字('輸入的數字')作爲字符的一部分,並用BigDecimal執行所有數學運算。
  6. 您故意忽略佈局管理器,然後花大力氣手動定位所有按鈕/標籤。不幸的是,如果調整大小,這會使你的應用程序中斷。你需要做的是把你的顯示器分成幾個(嵌套的)JPanel,每個都有相應的佈局管理器。如有必要,IDE和插件允許您可視化地設計此類系統。
  7. 您正在執行swing事件線程中的所有內容。雖然它在這裏起作用,但這不是最佳實踐,並且可能是破解或掛起應用程序的最快方法之一。應通過使用SwingUtilities.invokeLater();來調度所有圖形內容的創建和操作,包括創建主窗口。
  8. 您當前正在解析按鈕的標籤以選擇要執行的操作。這並不涉及國際化等問題。是時間許可證,請使用Strategy Pattern來封裝你的行爲。你至少需要兩套;一個用於將數字放入堆棧,另一個用於執行計算。這也意味着添加新操作(如pow函數)不需要修改代碼,只需添加新行爲(和按鈕)即可。

爲了進一步和未來的批判,在CodeReview上發佈代碼!

+0

,嗯,很好的答案 – mKorbel 2012-03-01 19:12:17

1
package Calculator; 

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class Carl extends JFrame { 

JTextField text1 = new JTextField(); 
JLabel label1 = new JLabel(" "); 
JButton button1 = new JButton("1"); 
JButton button2 = new JButton("2"); 
JButton button3 = new JButton("3"); 
JButton button4 = new JButton("4"); 
JButton button5 = new JButton("5"); 
JButton button6 = new JButton("6"); 
JButton button7 = new JButton("7"); 
JButton button8 = new JButton("8"); 
JButton button9 = new JButton("9"); 
JButton button10 = new JButton("0"); 
JButton button11 = new JButton("+"); 
JButton button12 = new JButton("-"); 
JButton button13 = new JButton("*"); 
JButton button14 = new JButton("/"); 
JButton button15 = new JButton("="); 
JButton button16 = new JButton("C"); 
JLabel blank1 = new JLabel(""); 
JLabel blank2 = new JLabel(""); 
JLabel blank3 = new JLabel(""); 
JLabel blank4 = new JLabel(""); 
Font times = new Font("Times New Roman", Font.BOLD, 18); 
int operation1; 
int operation2; 
int operation3; 
int operation4; 
String n1, n2; 
JPanel p1 = new JPanel(); 
JPanel p2 = new JPanel(); 

public Carl() { 
    setResizable(true); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setTitle("Calculator"); 
    setSize(600, 600); 
    button1.setForeground(Color.BLACK); 
    button2.setForeground(Color.BLACK); 
    button3.setForeground(Color.BLACK); 
    button4.setForeground(Color.BLACK); 
    button5.setForeground(Color.BLACK); 
    button6.setForeground(Color.BLACK); 
    button7.setForeground(Color.BLACK); 
    button8.setForeground(Color.BLACK); 
    button9.setForeground(Color.BLACK); 
    button10.setForeground(Color.BLACK); 
    button11.setForeground(Color.BLACK); 
    button12.setForeground(Color.BLACK); 
    button13.setForeground(Color.BLACK); 
    button14.setForeground(Color.BLACK); 
    button15.setForeground(Color.BLACK); 
    button16.setForeground(Color.BLACK); 
    button1.setBackground(Color.YELLOW); 
    button2.setBackground(Color.YELLOW); 
    button3.setBackground(Color.YELLOW); 
    button4.setBackground(Color.YELLOW); 
    button5.setBackground(Color.YELLOW); 
    button6.setBackground(Color.YELLOW); 
    button7.setBackground(Color.YELLOW); 
    button8.setBackground(Color.YELLOW); 
    button9.setBackground(Color.YELLOW); 
    button10.setBackground(Color.YELLOW); 
    button11.setBackground(Color.YELLOW); 
    button12.setBackground(Color.YELLOW); 
    button13.setBackground(Color.YELLOW); 
    button14.setBackground(Color.YELLOW); 
    button15.setBackground(Color.YELLOW); 
    button16.setBackground(Color.YELLOW); 
    button1.setToolTipText("one"); 
    button2.setToolTipText("two"); 
    button3.setToolTipText("three"); 
    button4.setToolTipText("four"); 
    button5.setToolTipText("five"); 
    button6.setToolTipText("six"); 
    button7.setToolTipText("seven"); 
    button8.setToolTipText("eight"); 
    button9.setToolTipText("nine"); 
    button10.setToolTipText("zero"); 
    button11.setToolTipText("addition"); 
    button12.setToolTipText("subtraction"); 
    button13.setToolTipText("multiplication"); 
    button14.setToolTipText("division"); 
    button15.setToolTipText("equal"); 
    button16.setToolTipText("clear"); 
    button1.setFont(times); 
    button2.setFont(times); 
    button3.setFont(times); 
    button4.setFont(times); 
    button5.setFont(times); 
    button6.setFont(times); 
    button7.setFont(times); 
    button8.setFont(times); 
    button9.setFont(times); 
    button10.setFont(times); 
    button11.setFont(times); 
    button12.setFont(times); 
    button13.setFont(times); 
    button14.setFont(times); 
    button15.setFont(times); 
    button16.setFont(times); 
    label1.setFont(times); 
    setLayout(new BorderLayout()); 
    p1.setLayout(new GridLayout(6, 3, 2, 2)); 
    p1.add(p2, BorderLayout.CENTER); 
    p1.add(label1); 
    p1.add(text1); 
    p1.add(blank3); 
    p1.add(button7); 
    p1.add(button8); 
    p1.add(button9); 
    p1.add(button11); 
    p1.add(button4); 
    p1.add(button5); 
    p1.add(button6); 
    p1.add(button12); 
    p1.add(button1); 
    p1.add(button2); 
    p1.add(button3); 
    p1.add(button13); 
    p1.add(button10); 
    p1.add(button16); 
    p1.add(button15); 
    p1.add(button14); 
    add(p1, BorderLayout.CENTER); 

    button1.addActionListener(new Listener1()); 
    button2.addActionListener(new Listener2()); 
    button3.addActionListener(new Listener3()); 
    button4.addActionListener(new Listener4()); 
    button5.addActionListener(new Listener5()); 
    button6.addActionListener(new Listener6()); 
    button7.addActionListener(new Listener7()); 
    button8.addActionListener(new Listener8()); 
    button9.addActionListener(new Listener9()); 
    button10.addActionListener(new Listener0()); 
    button11.addActionListener(new ListenerAdd()); 
    button12.addActionListener(new ListenerSub()); 
    button13.addActionListener(new ListenerMul()); 
    button14.addActionListener(new ListenerDiv()); 
    button15.addActionListener(new ListenerEqual()); 
    button16.addActionListener(new ListenerClear()); 
    setVisible(true); 

} 

private class Listener1 implements ActionListener { 

    public void actionPerformed(ActionEvent a) { 
     n1 = text1.getText(); 
     text1.setText(n1 + "1"); 
    } 
} 

private class Listener2 implements ActionListener { 

    public void actionPerformed(ActionEvent b) { 
     n1 = text1.getText(); 
     text1.setText(n1 + "2"); 
    } 
} 

private class Listener3 implements ActionListener { 

    public void actionPerformed(ActionEvent c) { 
     n1 = text1.getText(); 
     text1.setText(n1 + "3"); 
    } 
} 

private class Listener4 implements ActionListener { 

    public void actionPerformed(ActionEvent d) { 
     n1 = text1.getText(); 
     text1.setText(n1 + "4"); 
    } 
} 

private class Listener5 implements ActionListener { 

    public void actionPerformed(ActionEvent e) { 
     n1 = text1.getText(); 
     text1.setText(n1 + "5"); 
    } 
} 

private class Listener6 implements ActionListener { 

    public void actionPerformed(ActionEvent f) { 
     n1 = text1.getText(); 
     text1.setText(n1 + "6"); 
    } 
} 

private class Listener7 implements ActionListener { 

    public void actionPerformed(ActionEvent g) { 
     n1 = text1.getText(); 
     text1.setText(n1 + "7"); 
    } 
} 

private class Listener8 implements ActionListener { 

    public void actionPerformed(ActionEvent h) { 
     n1 = text1.getText(); 
     text1.setText(n1 + "8"); 
    } 
} 

private class Listener9 implements ActionListener { 

    public void actionPerformed(ActionEvent i) { 
     n1 = text1.getText(); 
     text1.setText(n1 + "9"); 
    } 
} 

private class Listener0 implements ActionListener { 

    public void actionPerformed(ActionEvent j) { 
     n1 = text1.getText(); 
     text1.setText(n1 + "0"); 
    } 
} 

private class ListenerAdd implements ActionListener { 

    public void actionPerformed(ActionEvent k) { 
     n2 = text1.getText(); 
     operation1 = 1; 
     text1.setText(""); 
    } 
} 

private class ListenerSub implements ActionListener { 

    public void actionPerformed(ActionEvent l) { 
     n2 = text1.getText(); 
     operation2 = 2; 
     text1.setText(""); 
    } 
} 

private class ListenerMul implements ActionListener { 

    public void actionPerformed(ActionEvent m) { 
     n2 = text1.getText(); 
     operation3 = 3; 
     text1.setText(""); 
    } 
} 

private class ListenerDiv implements ActionListener { 

    public void actionPerformed(ActionEvent n) { 
     n2 = text1.getText(); 
     operation4 = 4; 
     text1.setText(""); 
    } 
} 

private class ListenerEqual implements ActionListener { 

    public void actionPerformed(ActionEvent o) { 
     if (operation1 == 1) { 
      int a = Integer.parseInt(n2); 
      int b = Integer.parseInt(text1.getText()); 
      int sum = (a + b); 
      String sum1 = Integer.toString(sum); 
      text1.setText(sum1); 
     } else { 
      text1.getText(); 
     } 
     if (operation2 == 2) { 
      int a = Integer.parseInt(n2); 
      int b = Integer.parseInt(text1.getText()); 
      int dif = (a - b); 
      String dif1 = Integer.toString(dif); 
      text1.setText(dif1); 
     } else { 
      text1.getText(); 
     } 
     if (operation3 == 3) { 
      int a = Integer.parseInt(n2); 
      int b = Integer.parseInt(text1.getText()); 
      int product = (a * b); 
      String product1 = Integer.toString(product); 
      text1.setText(product1); 
     } else { 
      text1.getText(); 
     } 
     if (operation4 == 4) { 
      double a = Double.parseDouble(n2); 
      double b = Double.parseDouble(text1.getText()); 
      double quo = (a/b); 
      String quo1 = Double.toString(quo); 
      text1.setText(quo1); 
     } else { 
      text1.getText(); 
     } 
    } 
} 

private class ListenerClear implements ActionListener { 

    @Override 
    public void actionPerformed(ActionEvent p) { 
     text1.setText(""); 
    } 
} 

public static void main(String[] args) { 
    Carl frame = new Carl(); 
} 
} 

使用此代碼..