Java弱智计算器

学了一学期的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);
	}
}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值