我不知道如何重建这个简单的计算器 - 我必须使用调用方法而不是 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 );
}
});
}
}