[求助]switch 语句为什么不能用?
以下代码实现简易计算器 ,为什么使用中间的switch语句(被我注释了)编译不能通过 ,而换用 if嵌套 可以实现 请教..........................................
----------------------------------------------------------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Minicalc{
public static void main(String[] args){
JFrame frame=new JFrame("简易计算器");
Container pane=frame.getContentPane();
JTextField firstnumber=new JTextField(10);
JTextField secondnumber=new JTextField(10);
JTextField result=new JTextField(10);
JButton addButton=new JButton("+");
JButton subButton=new JButton("-");
JButton mulButton=new JButton("*");
JButton divButton=new JButton("/");
pane.setLayout(new GridLayout(5,2));
pane.add(new JLabel("Enter a number"));
pane.add(firstnumber);
pane.add(new JLabel("Enter a number"));
pane.add(secondnumber);
pane.add(new JLabel("Result"));
pane.add(result);
pane.add(addButton);
pane.add(subButton);
pane.add(mulButton);
pane.add(divButton);
DoMath listener=new DoMath(firstnumber,secondnumber,result);
addButton.addActionListener(listener);
subButton.addActionListener(listener);
mulButton.addActionListener(listener);
divButton.addActionListener(listener);
frame.pack();
frame.show();
}
}
class DoMath implements ActionListener{
private JTextField inputone,inputtwo,output;
//private JButton F;
DoMath(JTextField first,JTextField second,JTextField result){
inputone=first;
inputtwo=second;
output=result;
}
public void actionPerformed(ActionEvent e){
double first,second;
first=Double.parseDouble(inputone.getText().trim());
second=Double.parseDouble(inputtwo.getText().trim());
/* switch(e.getActionCommand().equals(F)){
case '+' :output.setText(String.valueOf(first+second));break;
case '-' :output.setText(String.valueOf(first-second));break;
case '*' :output.setText(String.valueOf(first*second));break;
case '/' :output.setText(String.valueOf(first/second));break;
} */
if (e.getActionCommand().equals("+"))
output.setText(String.valueOf(first+second));
else { if (e.getActionCommand().equals("-"))
output.setText(String.valueOf(first-second));
else {if (e.getActionCommand().equals("*"))
output.setText(String.valueOf(first*second)) ;
else
output.setText(String.valueOf(first/second));
}
}
}
}
--------------------------------------------------------------------------------------------------------------------------