简易计算机

Posted 北有孤鹜

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简易计算机相关的知识,希望对你有一定的参考价值。

package 考试题目_简易计算器;
	import java.awt.*;
	import javax.swing.*;
	import java.awt.event.*;
	public class Jisuanqi extends JFrame implements ActionListener{
		JTextField text1, text2, text3;
		JRadioButton btnAdd, btnSub, btnMul, btnDiv;
		ButtonGroup bg;
		JLabel num1, num2, result;
		JButton solve;
		Box base, boxH1, boxH2, boxH3, boxH4;
		
		public Jisuanqi(String name){
			super(name);
			setLayout(new FlowLayout());
			text1 = new JTextField(10);
			text2 = new JTextField(10);
			text3 = new JTextField(10);
			btnAdd = new JRadioButton("+");
			btnSub = new JRadioButton("-");
			btnMul = new JRadioButton("*");
			btnDiv = new JRadioButton("/");
			num1 = new JLabel("数一");
			num2 = new JLabel("数二");
			result = new JLabel("结果");
			solve = new JButton("=");
			solve.addActionListener(this);
			bg = new ButtonGroup();
			bg.add(btnAdd);
			bg.add(btnSub);
			bg.add(btnMul);
			bg.add(btnDiv);
					
			boxH1 = Box.createHorizontalBox();
			boxH1.add(num1);
			boxH1.add(Box.createHorizontalStrut(30));
			boxH1.add(text1);
			boxH2 = Box.createHorizontalBox();
			boxH2.add(btnAdd);
			boxH2.add(btnSub);
			boxH2.add(btnMul);
			boxH2.add(btnDiv);
			boxH3 = Box.createHorizontalBox();
			boxH3.add(num2);
			boxH3.add(Box.createHorizontalStrut(30));
			boxH3.add(text2);
			boxH4 = Box.createHorizontalBox();
			boxH4.add(result);
			boxH4.add(Box.createHorizontalStrut(30));
			boxH4.add(text3);
			base = Box.createVerticalBox();
			base.add(boxH1);
			base.add(Box.createVerticalStrut(25));
			base.add(boxH2);
			base.add(Box.createVerticalStrut(25));
			base.add(boxH3);
			base.add(Box.createVerticalStrut(25));
			base.add(solve);
			base.add(Box.createVerticalStrut(25));
			base.add(boxH4);
			add(base);
			
			setSize(300, 320);
			setVisible(true);
			validate();
			setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		}
		
		public void actionPerformed(ActionEvent e){
			double n = 0;
			double n1,n2;
			try{
					n1=Double.parseDouble(text1.getText());
					n2=Double.parseDouble(text2.getText());
					if(btnAdd.isSelected())
						n = n1+n2;
					else if(btnSub.isSelected())
						n = n1-n2;
					else if(btnMul.isSelected())
						n = n1*n2;
					else if(btnDiv.isSelected())
						n = n1/n2;
					text3.setText(String.valueOf(n));
					
			}catch(NumberFormatException nfe){
					text3.setText("请输入数字字符");
			}
			
		}
		
		public static void main(String args[]){
			new Jisuanqi("简易计算器");
		}

	}

  

以上是关于简易计算机的主要内容,如果未能解决你的问题,请参考以下文章

Java 简易计算器代码(只能整数的简易运算)

求JAVA编的简易计算器,急急急

Shell外壳的简易模拟

JS简易计算器——代码优化

js代码借助函数eval制作简易计算器

简易计算机:(JavaScript实现)