学了一学期的Java都没怎么敲过,感觉Java不是很自由,但确实很方便,调用各种接口,但还是不是很适应,一学期了,就最后用两小时写了个计算器。和那些写记事本的是真心没法比啊%>_
下面,贴一下代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class J_SimpleComputer {
static JTextField text1=new JTextField("",10);
static JTextField text2=new JTextField("",10);
static JTextField text3=new JTextField("",10);
static JComboBox operator=new JComboBox();
static char []oper={'+','-','*','/','='};
static void Init()
{
for(int i=0;i<4;i++)
{
operator.addItem(oper[i]);
}
}
static JButton deng=new JButton("=");
static String plus="+",minus="-",multi="*",divide="/",result;
static int tmp;
public static void main(String args[])
{
Init();
JFrame win=new JFrame("计算器");
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setLayout(new FlowLayout());
win.setBounds(600,200,500,100);
win.add(text1);
win.add(operator);
win.add(text2);
win.add(deng);
win.add(text3);
deng.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String x=text1.getText();
String y=text2.getText();
int a=Integer.parseInt(x);
int b=Integer.parseInt(y);
String op=operator.getSelectedItem().toString();
if(op.equals(divide))
{
if(b==0)
{
JOptionPane.showMessageDialog(null,"除0错误!");
}
else
{
tmp=a/b;
result=Integer.toString(tmp);
text3.setText(result);
}
}
else if(op.equals(multi))
{
tmp=a*b;
result=Integer.toString(tmp);
text3.setText(result);
}
else if(op.equals(plus))
{
tmp=a+b;
result=Integer.toString(tmp);
text3.setText(result);
}
else
{
tmp=a-b;
result=Integer.toString(tmp);
text3.setText(result);
}
}
});
win.setVisible(true);
}
}