java编写计算器源代码java编写计算器源代码
计算器的制作
import java.awt.*;
import java.awt.event.*;
class ComputerExe extends Frame implements ActionListener
{
Button b1,b2,b3,b4;
TextField t1,t2,t3;
Label l1,l2;
public static void main(String[] args)//程序入口
{
new ComputerExe();//创建本窗体...
java编写计算器源代码
计算器的制作
import java.awt.*;
import java.awt.event.*;
class ComputerExe extends Frame implements ActionListener
{
Button b1,b2,b3,b4;
TextField t1,t2,t3;
Label l1,l2;
public static void main(String[] args)//程序入口
{
new ComputerExe();//创建本窗体对象
}
ComputerExe()//构造方法
{
super("四则运算");
setBounds(100,100,300,200);
setVisible(true);
b1=new Button("加");
b2=new Button("减");
b3=new Button("乘");
b4=new Button("除");
t1=new TextField(15);
t2=new TextField(15);
t3=new TextField(15);
l1=new Label("");
l2=new Label("=");
l1.setBackground(Color.yellow);
l1.setForeground(Color.red);
l2.setBackground(Color.yellow);
l2.setForeground(Color.red);
t3.setEditable(false);
setLayout(new FlowLayout());//更改窗体框架的布局
add(t1);
add(l1);
add(t2);
add(l2);
add(t3);
add(b1);
add(b2);
add(b3);
add(b4);
setVisible(true);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}//构造方法结束
public void actionPerformed(ActionEvent e)
{ double n1,n2,n3;
if(e.getSource()==b1)
{
try{
n1=Double.parseDouble(t1.getText());
n2=Double.parseDouble(t2.getText());
n3=n1+n2;
t3.setText(String.valueOf(n3));
l1.setText("+");
}catch(NumberFormatException w)
{
t3.setText("操作数应该为数字~");
}
}
if(e.getSource()==b2)
{
try{
n1=Double.parseDouble(t1.getText());
n2=Double.parseDouble(t2.getText());
n3=n1-n2;
t3.setText(String.valueOf(n3));
l1.setText("-");
}catch(NumberFormatException w)
{
t3.setText("操作数应该为数字~");
}
}
if(e.getSource()==b3)
{
try{
n1=Double.parseDouble(t1.getText());
n2=Double.parseDouble(t2.getText());
n3=n1*n2;
t3.setText(String.valueOf(n3));
l1.setText("*");
}catch(NumberFormatException w)
{
t3.setText("操作数应该为数字~");
}
}
if(e.getSource()==b4)
{
try{
n1=Double.parseDouble(t1.getText());
n2=Double.parseDouble(t2.getText());
n3=n1/n2;
t3.setText(String.valueOf(n3));
l1.setText("/");
}catch(NumberFormatException w)
{
t3.setText("操作数应该为数字~");
}
}
}
}//类结束
本文档为【java编写计算器源代码】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。