-2

我不知道如何重建这个简单的计算器 - 我必须使用调用方法而不是 switch。特定操作员必须动态运行适当的方法。你有什么建议吗?提前致谢!

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

1 回答 1

0

如果您不允许使用 switch 或有其他原因不使用它,您可以使用地图来代替。

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

然后你可以简单地执行:

Command r = map.get(sop.charAt(0));
if (r != null) {
    r.execute(num1, num2);
} else {
    throw new IllegalArgumentException(); // I'd recommend using assertions here, like assert n != null.
}

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

但是,当然,带有 switch 的原始解决方案更容易且更具可读性。

于 2013-01-10T21:31:35.943 回答