2013-01-10 64 views
-2

我不知道如何重建這個簡單的計算器 - 我必須使用調用方法,而不是開關。特定的操作員必須運行動​​態適當的方法。你有什麼建議嗎? 在此先感謝!使用反射而不是開關

import javax.swing.*; 
import java.util.*; 
import java.awt.*; 
import java.awt.event.*; 
public class TokenTest extends JFrame 
{ 
private JLabel prompt; 
private JTextField input; 
private JLabel result; 
public TokenTest() 
    { 
    super("Testing Class StringTokenizer"); 
    Container c = getContentPane(); 
    c.setLayout(new FlowLayout()); 
    prompt = new JLabel("Enter number1 operator number2 and press Enter"); 
    c.add(prompt); 
    input = new JTextField(10); 
    input.addActionListener(new ActionListener() 
       { 
     public void actionPerformed(ActionEvent e) 
      { 
      String stringToTokenize = e.getActionCommand(); 
      StringTokenizer tokens = new StringTokenizer(stringToTokenize); 
      double res; 
      double num1 = Integer.parseInt(tokens.nextToken()); 
      String sop = tokens.nextToken(); 
      double num2 = Integer.parseInt(tokens.nextToken()); 

      switch (sop.charAt(0)) { 
      case '+' : res = num1 + num2; break; 
      case '-' : res = num1 - num2; break; 
      case '*' : res = num1 * num2; break; 
      case '/' : res = num1/num2; break; 
      default : throw new IllegalArgumentException(); 
      }   
      result.setText(String.valueOf(res));     
     } 
    }); 
    c.add(input); 

    result = new JLabel(""); 
    c.add(result); 

    setSize(375, 160); 
    show(); 
} 
    public static void main(String args[]) 
    { 
    TokenTest app = new TokenTest(); 

    app.addWindowListener(new WindowAdapter() 
     { 
     public void windowClosing(WindowEvent e) 
      { 
      System.exit(0); 
     } 
    }); 
} 
} 
+3

爲什麼在這裏需要反射? –

+0

這是功課嗎? – MrSmith42

+0

我看不到如何在這裏使用反射,你沒有呼叫任何類 – MadProgrammer

回答

0

如果您不允許使用開關或有其他原因不使用它,您可以使用地圖代替。

Map<Character, Command> map = new HashMap<>(); 
map.put('+', sumCommand); 
map.put('-', subCommand); 
map.put('*', multCommand); 
map.put('/', divCommand); 

然後,你可以簡單地執行:

Command接口及其實現的人會這個樣子。

public interface Command { 
    double execute(double num1, double num2); 
} 

public class SumCommand implements Command { 
    public double execute(double num1, double num2) { 
     return num1 + num2; 
    } 
} 

但是,切換原來的解決方案更容易,更具可讀性。