本文目录一览:
- 1、用JAVA编写一个简单的计算器,要求如下
- 2、如何用JAVA编写计算器?
- 3、用Java编写一个简单的计算器程序
- 4、怎么用JAVA编程编写一个计算器?
- 5、用JAVA编写一个计算器
- 6、编写计算器java
用JAVA编写一个简单的计算器,要求如下
然后 通过输入 显示结果,比如说:
以下是上图计算器的代码:
package Computer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Count extends JApplet implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField textField = new JTextField("请输入");
String operator = "";//操作
String input = "";//输入的 式子
boolean flag = true;
// boolean flag1 = true;
// boolean flag2 = true;
public void init()//覆写Applet里边的init方法
{
Container C = getContentPane();
JButton b[] = new JButton[16];
JPanel panel = new JPanel();
C.add(textField, BorderLayout.NORTH);
C.add(panel,BorderLayout.CENTER);
panel.setLayout(new GridLayout(4, 4,5,5));
String name[]={"7","8","9","+","4","5","6","-","1","2","3","*","0","C","=","/"};//设置 按钮
for(int i=0;i16;i++)//添加按钮
{
b[i] = new JButton(name[i]);
b[i].setBackground(new Color(192,192,192));
b[i].setForeground(Color.BLUE);//数字键 设置为 蓝颜色
if(i%4==3)
b[i].setForeground(Color.RED);
b[i].setFont(new Font("宋体",Font.PLAIN,16));//设置字体格式
panel.add(b[i]);
b[i].addActionListener(this);
}
b[13].setForeground(Color.RED);//非数字键,即运算键设置为红颜色
b[13].setForeground(Color.RED);
}
public void actionPerformed(ActionEvent e)
{
int cnt = 0;
String actionCommand = e.getActionCommand();
if(actionCommand.equals("+")||actionCommand.equals("-")||actionCommand.equals("*") ||actionCommand.equals("/"))
input +=" "+actionCommand+" ";//设置输入,把输入的样式改成 需要的样子
else if(actionCommand.equals("C"))
input = "";
else if(actionCommand.equals("="))//当监听到等号时,则处理 input
{
input+= "="+compute(input);
textField.setText(input);
input="";
cnt = 1;
}
else
input += actionCommand;//数字为了避免多位数的输入 不需要加空格
if(cnt==0)
textField.setText(input);
}
private String compute(String input)//即1237 的 样例
{
String str[];
str = input.split(" ");
StackDouble s = new StackDouble();
double m = Double.parseDouble(str[0]);
s.push(m);
for(int i=1;istr.length;i++)
{
if(i%2==1)
{
if(str[i].compareTo("+")==0)
{
double help = Double.parseDouble(str[i+1]);
s.push(help);
}
if(str[i].compareTo("-")==0)
{
double help = Double.parseDouble(str[i+1]);
s.push(-help);
}
if(str[i].compareTo("*")==0)
{
double help = Double.parseDouble(str[i+1]);
double ans = s.peek();//取出栈顶元素
s.pop();//消栈
ans*=help;
s.push(ans);
}
if(str[i].compareTo("/")==0)
{
double help = Double.parseDouble(str[i+1]);
double ans = s.peek();
s.pop();
ans/=help;
s.push(ans);
}
}
}
double ans = 0d;
while(!s.isEmpty())
{
ans+=s.peek();
s.pop();
}
String result = String.valueOf(ans);
return result;
}
public static void main(String args[])
{
JFrame frame = new JFrame("Count");
Count applet = new Count();
frame.getContentPane().add(applet, BorderLayout.CENTER);
applet.init();//applet的init方法
applet.start();//线程开始
frame.setSize(350, 400);//设置窗口大小
frame.setVisible(true);//设置窗口可见
}
}
如何用JAVA编写计算器?
package Test;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Calculator extends JFrame{
private float op1,op2;//定义两个变量存放需要运算的值
private String str="";//定义str去和text进行交叉赋值
private String opr,co;//opr存放符合,co用来存放复制的内容
private double re;//用来存放运算的结果
private boolean bo=false;//是否进行了+-*/运算
private boolean btime=false;//时间开关
Container contentpane=this.getContentPane();
JPanel panel1=new JPanel(new BorderLayout()),
panel2=new JPanel(new FlowLayout()),
panel3=new JPanel(new GridLayout(4,5)),
panel4=new JPanel(new BorderLayout()),
panel5=new JPanel(new BorderLayout());
//菜单栏
JMenuBar menubar=new JMenuBar();
JMenu edit=new JMenu("编辑(E)"),
find=new JMenu("查看(V)"),
help=new JMenu("帮助(H)");
JMenuItem copy=new JMenuItem("复制(C)",'C'),
paste=new JMenuItem("粘贴(P)",'P'),
standard=new JMenuItem("标准型(T)",'T'),
science=new JMenuItem("科学型(S)",'S'),
numarray=new JMenuItem("数字分组(I)",'I'),
helptopic=new JMenuItem("帮助主题(H)",'H'),
aboutcal=new JMenuItem("关于计算器(A)",'A');
//输入文本框
JTextField text=new JTextField(25);
//数字键
JButton one=new JButton("1"),
two=new JButton("2"),
three=new JButton("3"),
four=new JButton("4"),
five=new JButton("5"),
six=new JButton("6"),
seven=new JButton("7"),
eight=new JButton("8"),
nine=new JButton("9"),
zero=new JButton("0");
//功能键
JButton division=new JButton("/"),
multiply=new JButton("*"),
addition=new JButton("+"),
subtration=new JButton("-"),
sqrt=new JButton("sqrt"),
residual=new JButton("%"),
sign=new JButton("+/-"),
dot=new JButton("."),
reciprocal=new JButton("1/X"),
amount=new JButton("="),
backspace=new JButton("Backspace"),
ce=new JButton("CE"),
c=new JButton("C"),
time=new JButton("time");
public Calculator() {
contentpane.setLayout(new BorderLayout());
//textField文本从右边开始写
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.setText("0.");
//菜单栏添加
edit.add(copy);
edit.add(paste);
find.add(standard);
find.add(science);
find.addSeparator();
find.add(numarray);
help.add(helptopic);
help.addSeparator();
help.add(aboutcal);
//把组件添加至容器中
menubar.add(edit);
menubar.add(find);
menubar.add(help);
panel1.add(menubar,"North");
panel1.add(text,"West");
//添加数字、功能键至panel2、panel3
panel2.add(backspace);
panel2.add(ce);
panel2.add(c);
panel2.add(time);
panel3.add(seven);
panel3.add(eight);
panel3.add(nine);
panel3.add(division);
panel3.add(sqrt);
panel3.add(four);
panel3.add(five);
panel3.add(six);
panel3.add(multiply);
panel3.add(residual);
panel3.add(one);
panel3.add(two);
panel3.add(three);
panel3.add(subtration);
panel3.add(reciprocal);
panel3.add(zero);
panel3.add(sign);
panel3.add(dot);
panel3.add(addition);
panel3.add(amount);
panel4.add(panel2,"North");
panel4.add(panel3,"West");
panel5.add(panel1,"North");
panel5.add(panel4,"West");
contentpane.add(panel5,"North");
//事件
//助记符
edit.setMnemonic('E');
find.setMnemonic('V');
help.setMnemonic('H');
//快捷键
KeyStroke kcopy=KeyStroke.getKeyStroke(KeyEvent.VK_C,Event.CTRL_MASK);
copy.setAccelerator(kcopy);
KeyStroke kpaste=KeyStroke.getKeyStroke(KeyEvent.VK_V,Event.CTRL_MASK);
paste.setAccelerator(kpaste);
//0-9、.的显示事件
actionlistener1 al1=new actionlistener1();
one.addActionListener(al1);
two.addActionListener(al1);
three.addActionListener(al1);
four.addActionListener(al1);
five.addActionListener(al1);
six.addActionListener(al1);
seven.addActionListener(al1);
eight.addActionListener(al1);
nine.addActionListener(al1);
//小数点的ActionListener事件
dot.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int count;
count=str.length();
//1.第一位就为.时改变text中内容为:"0."
if(count==0){
str="0.";
text.setText(str);
}
//2.不可以重复按"."
else {if(!str.contains(".")){
str+=".";
text.setText(str);
}
else
System.out.println("您再点的话,输入的将不再是小数了!");
}
}
});
//如果第一位是0那么第二位就不可以为0
zero.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int count;
count=str.length();
if(bo){
if(!(str.contains("0")count==1)){
str="";
str+="0";
text.setText(str);
}else
System.out.println("您再点的话,输入的将不再是数字了!");
}
else{
if(!(str.contains("0")count==1)){
str+="0";
text.setText(str);
}else
System.out.println("您再点的话,输入的将不再是数字了!");
}
bo=false;
}
});
//+、-、*、/、%运算
actionlistener3 al3=new actionlistener3();
addition.addActionListener(al3);
subtration.addActionListener(al3);
multiply.addActionListener(al3);
division.addActionListener(al3);
residual.addActionListener(al3);
//CE和C清空按钮时间
actionlistener2 al2=new actionlistener2();
ce.addActionListener(al2);
c.addActionListener(al2);
//退格键
backspace.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int count;
count=str.length()-1;
if(bo==false){
if(count=0){
str=str.substring(0,count);
text.setText(str);
}
else
text.setText("0.");
}else
System.out.println("您现在正进行法则运算!");
}
});
//求平方根
sqrt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int count;
count=str.length();
if(count!=0){
op1=Float.parseFloat(text.getText());
re=Math.sqrt(op1);
String str1=String.valueOf(re);
text.setText(str1);
str="";
}
else
System.out.println("您现在的按sqrt键毫无意义");
}
});
//求倒数
reciprocal.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int count;
count=str.length();
if(count!=0){
op1=Float.parseFloat(text.getText());
if(op1!=0){
re=1/op1;
String str1=String.valueOf(re);
text.setText(str1);
str=str1;
}
else{
text.setText("除数不可以为0的");
str="";
}
}
else
System.out.println("您现在的按1/X键毫无意义");
}
});
//=事件
amount.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
op2=Float.parseFloat(str);
//需判断进行那种运算法则
if(opr=="+"){//加法运算
re=op1+op2;
String str1=String.valueOf(re);
text.setText(str1);
str=String.valueOf(re);
}else{
if(opr=="-"){//减法运算
re=op1-op2;
String str1=String.valueOf(re);
text.setText(str1);
str=String.valueOf(re);
}else{
if(opr=="*"){//乘法运算
re=op1*op2;
String str1=String.valueOf(re);
text.setText(str1);
str=String.valueOf(re);
}else{
if(opr=="/"op2!=0){//除法运算
re=op1/op2;
String str1=String.valueOf(re);
text.setText(str1);
str=String.valueOf(re);
}else{
if(opr=="%"){//取余运算
re=op1%op2;
String str1=String.valueOf(re);
text.setText(str1);
str="";
}
else if(op2==0){
text.setText("除数不可以为0的");
str="";
}
}
}
}
}
//打印看看
System.out.print(op1);
System.out.print(opr);
System.out.print(op2+"=");
System.out.print(re);
System.out.println();
}
});
//复制事件
copy.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int count;
count=str.length();
if(count!=0){
co=text.getText();
}
else
System.out.println("没有可复制的对象");
}
});
//粘贴事件
paste.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
str=co;
text.setText(str);
}
});
//时间事件
time.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(btime==false){
String st=(new Date()).toString();
text.setText(st);
str="";
btime=true;
}
else{
text.setText(str);
btime=false;
}
}
});
//+/-事件
sign.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int a=Integer.valueOf(str);
a=a*(-1);
str=String.valueOf(a);
text.setText(str);
}
});
}
//定义1-9按钮在text中显示的内部类
class actionlistener1 implements ActionListener{
public void actionPerformed(ActionEvent e){
JButton button=(JButton)e.getSource();
String btext=button.getText();
//如果第一位为0再输入其他非零的整数时将零忽略
if(bo){
if(str.indexOf("0")==0str.length()==1){
str="";
str+=btext;
text.setText(str);
}else{
str="";
str+=btext;
text.setText(str);}
}else{
if(str.indexOf("0")==0str.length()==1){
str="";
str+=btext;
text.setText(str);
}else{
str+=btext;
text.setText(str);
}
}
bo=false;
}
}
//定义清空text中内容的内部类
class actionlistener2 implements ActionListener{
public void actionPerformed(ActionEvent e){
str="";
text.setText("0.");
}
}
//定义+、-、*、/、%运算的内部类
class actionlistener3 implements ActionListener{
public void actionPerformed(ActionEvent e){
int count;
count=str.length();
if(count!=0){
JButton button=(JButton)e.getSource();
opr=button.getText();
op1=Float.parseFloat(str);
bo=true;
}
else
System.out.println("您现在的按键毫无意义!");
}
}
public static void main(String[] args){
Calculator cc=new Calculator();
cc.pack();
cc.setResizable(false);//不可最大化
cc.setVisible(true);
cc.setTitle("计算器");
cc.setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension scmsize=Toolkit.getDefaultToolkit().getScreenSize();
int w=cc.getSize().width;
int h=cc.getSize().height;
int x=(scmsize.width-w)/2;
int y=(scmsize.height-h)/2;
cc.setLocation(x, y);
}
}
用Java编写一个简单的计算器程序
import java.awt.*;
import java.awt.event.*;
public class CalcAppDemo extends Frame{
private TextField t_result;
private Panel p_main; //主面板
private Panel p_num; //数字面板
private Panel p_oper; //操作符面板
private Panel p_show; //显示面板
private Button b_num[]; //数字按钮
private Button b_oper[]; //操作符面板
public CalcAppDemo(String title){
setTitle(title);
t_result = new TextField("0.0", 21);
p_main = new Panel();
p_num = new Panel();
p_oper = new Panel();
p_show = new Panel();
p_main.setLayout(new BorderLayout());
p_num.setLayout(new GridLayout(4, 3, 1, 1));
p_oper.setLayout(new GridLayout(4, 2, 1, 1));
b_num = new Button[12];
for(int i=0; i9; i++)
{
b_num[i] = new Button(new Integer(i+1).toString());
}
b_num[9] = new Button("0");
b_num[10] = new Button("cls");
b_num[11] = new Button(".");
for(int i=0; i12; i++)
{
p_num.add(b_num[i]);
}
b_oper = new Button[8];
b_oper[0] = new Button("+");
b_oper[1] = new Button("-");
b_oper[2] = new Button("*");
b_oper[3] = new Button("/");
b_oper[4] = new Button("pow");
b_oper[5] = new Button("sqrt");
b_oper[6] = new Button("+/-");
b_oper[7] = new Button("=");
for(int i=0; i8; i++) //
{
p_oper.add(b_oper[i]);
}
t_result.setEditable(false);
p_show.add(t_result, BorderLayout.NORTH);
p_main.add(p_show, BorderLayout.NORTH);
p_main.add(p_num, BorderLayout.WEST);
p_main.add(p_oper, BorderLayout.EAST);
this.add(p_main, BorderLayout.CENTER);
setSize(400, 400);
setResizable(false);
pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
ButtonListener b1 = new ButtonListener();
for(int i=0; i12; i++)
{
b_num[i].addActionListener(b1);
}
for(int i=0; i8; i++)
{
b_oper[i].addActionListener(b1);
}
}
class ButtonListener implements ActionListener
{
private String lastOp; //存储上一此操作符
private String strVal; //存储数字对应的字符串
private double total; //总数
private double number; //存储新输入的数
private boolean firsttime; //判断是否第一次按下的是操作符按钮
private boolean operatorPressed;//判断是否已经按过操作符按钮
ButtonListener()
{
firsttime = true;
strVal = "";
}
//事件处理器
public void actionPerformed(ActionEvent e)
{
String s = ((Button)e.getSource()).getLabel().trim();
if(Character.isDigit(s.charAt(0)))
{//判断是操作数还是操作符
handleNumber(s);
}
else
{
calculate(s);
}
}
//判断是一元操作符还是二元操作符,并根据操作符类型做计算
void calculate(String op)
{
operatorPressed = true;
if(firsttime! isUnary(op))
{
total = getNumberOnDisplay();
firsttime = false;
}
if(isUnary(op))
{
handleUnaryOp(op);
}
else if(lastOp != null)
{
handleBinaryOp(lastOp);
}
if(! isUnary(op))
{
lastOp = op;
}
}
//判断是否一元操作符
boolean isUnary(String s)
{
return s.equals("=")
||s.equals("cls")||s.equals("sqrt")
||s.equals("+/-")||s.equals(".");
}
//处理一元操作符
void handleUnaryOp(String op)
{
if(op.equals("+/-"))
{//
number = negate(getNumberOnDisplay() + "");
t_result.setText("");
t_result.setText(number + "");
return;
}else if(op.equals("."))
{
handleDecPoint();
return;
}else if(op.equals("sqrt"))
{
number = Math.sqrt(getNumberOnDisplay());
t_result.setText("");
t_result.setText(number + "");
return;
}else if(op.equals("="))
{//
if(lastOp!= null !isUnary(lastOp))
{
handleBinaryOp(lastOp);
}
lastOp = null;
firsttime = true;
return;
}else
{
clear();
}
}
//处理二元运算符
void handleBinaryOp(String op)
{
if(op.equals("+"))
{
total +=number;
}else if(op.equals("-"))
{
total -=number;
}else if(op.equals("*"))
{
total *=number;
}else if(op.equals("/"))
{
try
{
total /=number;
}catch(ArithmeticException ae){}
}else if(op.equals("pow"))
total = Math.pow(total, number);
//t_result.setText("");
lastOp = null;
// strVal = "";
number = 0;
t_result.setText(total + "");
}
//该方法用于处理数字按钮
void handleNumber(String s)
{
if(!operatorPressed)
{
strVal += s;
}else
{
operatorPressed = false;
strVal = s;
}
//
number = new Double(strVal).doubleValue();
t_result.setText("");
t_result.setText(strVal);
}
//该方法用于按下"."按钮
void handleDecPoint()
{
operatorPressed = false;
//
if(strVal.indexOf(".")0)
{
strVal += ".";
}
t_result.setText("");
t_result.setText(strVal);
}
//该方法用于将一个数求反
double negate(String s)
{
operatorPressed = false;
//如果是一个整数,去掉小数点后面的0
if(number == (int)number)
{
s = s.substring(0,s.indexOf("."));
}
//如果无"-"增加在该数的前面
if(s.indexOf("-")0)
{
strVal = "-" + s;
}
else
{
strVal = s.substring(1);
}
return new Double(strVal).doubleValue();
}
//将显示框中的值转换成Double
double getNumberOnDisplay()
{
return new Double(t_result.getText()).doubleValue();
}
//清除屏幕并设置所有的标识
void clear()
{
firsttime = true;
lastOp = null;
strVal = "";
total = 0;
number = 0;
t_result.setText("0");
}
}
public static void main(String[] args) {
CalcAppDemo c = new CalcAppDemo("简单的计算器程序");
c.setVisible(true);
}
}
怎么用JAVA编程编写一个计算器?
打开IED:打开自己java编程的软件,采用的是eclipse软件。
建立java工程。
编写类。
编写类的详细步骤
1.类的基本结构:
由于这里用到了界面,所以要进行窗口界面的编程,按钮事件的处理,和计算处理界面;
package MyCaculator;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyCaculator extends JFrame {
private int add=1,sub=2,mul=3,div=4;
private int op=0;
boolean ifOp;
private String output="0";
private Button[] jba=new Button[]{new Button("7"),new Button("8"),
new Button("9"),new Button("+"),
new Button("4"),new Button("5"),new Button("6"),new Button("-"),
new Button("1"),new Button("2"),new Button("3"),new Button("*"),
new Button("0"),new Button("."),new Button("="),new Button("/")};
private JPanel jpt=new JPanel();
private JPanel jpb=new JPanel();
private JTextField jtf=new JTextField("");
private MyCaculator(){
}
private void operate(String x){
}
public String add(String x){
return output;
}
public String subtract(String x){
return output;
}
public String multiply(String x){
return output;
}
public String divide(String x){
return output;
}
public String Equals(String x){
return output;
}
public void opClean(){
}
class setOperate_Act implements ActionListener{
public void actionPerformed(ActionEvent e) {
}
}
class setLabel_Act implements ActionListener{
public void actionPerformed(ActionEvent e) {
}
}
public static void main(String[] args) {
}
}
2.建立构造方法:
所谓构造方法就是,对自己的主类进行初始化,代码如下:
private MyCaculator(){
jpt.setLayout(new BorderLayout());
jpt.add(jtf);
this.add(jpt,BorderLayout.NORTH);
jpb.setLayout(new GridLayout(4,4));
for(int i=0;ijba.length;i++){
jpb.add(jba[i]);
if(i==3||i==7||i==11||i==15||i==14)
jba[i].addActionListener(new setOperate_Act());
else
jba[i].addActionListener(new setLabel_Act());
}
this.add(jpb,BorderLayout.CENTER);
this.setSize(250, 200);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
3.建立数据计算方法
这里的数据计算方法有6个,一个是主方法其他几个是加减乘除的处理方法,代码如下:
private void operate(String x){
double x1=Double.valueOf(x);
double y=Double.valueOf(output);
switch(op){
case 0:output=x;break;
case 1:output=String.valueOf(y+x1);break;
case 2:output =String.valueOf(y-x1);break;
case 3:output =String.valueOf(y*x1);break;
case 4:
if(x1!=0) output=String.valueOf(y/x1);
else output="不能为0";
break;
}
}
public String add(String x){
operate(x);
op=add;
return output;
}
public String subtract(String x){
operate(x);
op=sub;
return output;
}
public String multiply(String x){
operate(x);
op=mul;
return output;
}
public String divide(String x){
operate(x);
op=div;
return output;
}
public String Equals(String x){
operate(x);
op=0;
return output;
}
public void opClean(){
op=0;
output ="0";
}
4.事件处理方法
这里的时间处理方法,没有建立一个整体的方法,二是在为了便于处理的方法,将按钮事件分成两个部分,并采用两个子类来实现,这两个类时内部类要写在主类内部的,代码如下:
class setOperate_Act implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jba[3]){
jtf.setText(add(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[7]){
jtf.setText(subtract(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[11]){
jtf.setText(multiply(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[15]){
jtf.setText(divide(jtf.getText()));
ifOp=true;
}
else if(e.getSource()==jba[14]){
jtf.setText(Equals(jtf.getText()));
ifOp=true;
}
}
}
class setLabel_Act implements ActionListener{
public void actionPerformed(ActionEvent e) {
Button tempb=(Button)e.getSource();
if(ifOp){
jtf.setText(tempb.getLabel());
ifOp=false;
}else {
jtf.setText(jtf.getText()+tempb.getLabel());
}
}
}
5.建立main方法:
要想实现我们的代码,我们需在main方法中,实例化我们的对象。
public static void main(String[] args) {
new MyCaculator();
}
用JAVA编写一个计算器
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Jisuanqi extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
Result result = new Result(); // 定义text的面板
Number_Key number_key = new Number_Key(); // 定义按钮面板
// 当点击按钮+、-、*、/时,com = true
boolean com = false;
// 当i=0时说明是我们第一次输入,字符串text不会累加
int i = 0;
// 存放text的内容
String text = "";
// 存放点击按钮+、-、*、/之前的数值
double defbutton = 0;
// +、-、*、/的代号分别为1,2,3,4
int symbol = 0;
// 构造函数
Jisuanqi() {
super("WangJiao"); // 设定标题
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设定关闭窗体时退出程序
JPanel pane = new JPanel(); // 定义主面板
pane.setLayout(new BorderLayout());
setBounds(380, 220, 30, 80); // 前两个参数是在屏幕上显示的坐标,后两个是大小
// 替换图标
ImageIcon icon = new ImageIcon("F:1.GIF");
// Jisuanqi.class.getResource("APPLE.GIF")
// );
setIconImage(icon.getImage());
pane.add(result, BorderLayout.NORTH);
pane.add(number_key, BorderLayout.CENTER);
pane.add(number_key.equal, BorderLayout.SOUTH);
number_key.one.addActionListener(this); // 对1按钮添加监听事件
number_key.two.addActionListener(this); // 对2按钮添加监听事件
number_key.three.addActionListener(this); // 对3按钮添加监听事件
number_key.four.addActionListener(this); // 对4按钮添加监听事件
number_key.five.addActionListener(this); // 对5按钮添加监听事件
number_key.six.addActionListener(this); // 对6按钮添加监听事件
number_key.seven.addActionListener(this); // 对7按钮添加监听事件
number_key.eight.addActionListener(this); // 对8按钮添加监听事件
number_key.nine.addActionListener(this); // 对9按钮添加监听事件
number_key.zero.addActionListener(this); // 对0按钮添加监听事件
number_key.ce.addActionListener(this); // 对置零按钮添加监听事件
number_key.plus.addActionListener(this); // 对+按钮添加监听事件
number_key.equal.addActionListener(this); // 对=按钮添加监听事件
number_key.sub.addActionListener(this); // 对-按钮添加监听事件
number_key.mul.addActionListener(this); // 对*按钮添加监听事件
number_key.div.addActionListener(this); // 对/按钮添加监听事件
number_key.point.addActionListener(this); // 对.按钮添加监听事件
setContentPane(pane);
pack(); // 初始化窗体大小为正好盛放所有按钮
}
// 各个按钮触发的事件
public void actionPerformed(ActionEvent e) {
/*
* 如果是点击数字按钮那么先要判断是否在此之前点击了+、-、*、/、=,如果是那么com=true 如果没有com=
* false;或者是否点击数字键,如果是i = 1,如果没有 i = 0;
*/
if (e.getSource() == number_key.one) {
if (com || i == 0) {
result.text.setText("1");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "1");
}
} else if (e.getSource() == number_key.two) {
if (com || i == 0) {
result.text.setText("2");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "2");
}
} else if (e.getSource() == number_key.three) {
if (com || i == 0) {
result.text.setText("3");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "3");
}
} else if (e.getSource() == number_key.four) {
if (com || i == 0) {
result.text.setText("4");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "4");
}
} else if (e.getSource() == number_key.five) {
if (com || i == 0) {
result.text.setText("5");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "5");
}
} else if (e.getSource() == number_key.six) {
if (com || i == 0) {
result.text.setText("6");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "6");
}
} else if (e.getSource() == number_key.seven) {
if (com || i == 0) {
result.text.setText("7");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "7");
}
} else if (e.getSource() == number_key.eight) {
if (com || i == 0) {
result.text.setText("8");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "8");
}
} else if (e.getSource() == number_key.nine) {
if (com || i == 0) {
result.text.setText("9");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "9");
}
}
/*
* 对于0这个按钮有一定的说法,在我的程序里不会出现如00000这样的情况,我加了判断条件就是
* 如果text中的数值=0就要判断在这个数值中是否有.存在?如果有那么就在原来数值基础之上添 加0;否则保持原来的数值不变
*/
else if (e.getSource() == number_key.zero) { // result.text.getText()是得到text里内容的意思
if (com || i == 0) {
result.text.setText("0");
com = false;
i = 1;
} else {
text = result.text.getText();
if (Float.parseFloat(text) 0 || Float.parseFloat(text) 0) { // Float.parseFloat(text)就是类型转换了,下面都是一样
result.text.setText(text + "0");
} else {
if (text.trim().indexOf(".") == -1) {
result.text.setText(text);
} else {
result.text.setText(text + "0");
}
}
}
} else if (e.getSource() == number_key.ce) {
result.text.setText("0");
i = 0;
com = true;
// text = "";
defbutton = 0;
}
/*
* 本程序不会让一个数值中出现2个以上的小数点.具体做法是:判断是否已经存在.存在就不添加, 不存在就添加.
*/
else if (e.getSource() == number_key.point) {
if (com || i == 0) {
result.text.setText("0.");
com = false;
i = 1;
} else {
text = result.text.getText();
if (text.trim().indexOf(".") == -1) {
result.text.setText(text + ".");
} else {
result.text.setText(text);
}
}
} // 获得点击+之前的数值
else if (e.getSource() == number_key.plus) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 1;
} // 获得点击-之前的数值
else if (e.getSource() == number_key.sub) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 2;
} // 获得点击*之前的数值
else if (e.getSource() == number_key.mul) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
System.out.println(defbutton);
symbol = 3;
} // 获得点击/之前的数值
else if (e.getSource() == number_key.div) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 4;
} else if (e.getSource() == number_key.equal) {
switch (symbol) {
case 1: { // 计算加法
double ad = defbutton
+ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 2: { // 计算减法
double ad = defbutton
- Double.parseDouble(result.text.getText());
result.text.setText(String.valueOf(ad));
i = 0;
text = "";
break;
}
case 3: { // 计算乘法
double ad = defbutton
* Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 4: { // 计算除法
double ad = defbutton
/ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
}
System.out.println(com);
}
System.out.println(result.text.getText());
}
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Jisuanqi loveyou = new Jisuanqi();
loveyou.show();
}
}
// 计算器数字按钮定义面板
class Number_Key extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JButton zero = new JButton("0"); // 数字键0
JButton one = new JButton("1"); // 数字键1
JButton two = new JButton("2"); // 数字键2
JButton three = new JButton("3"); // 数字键3
JButton four = new JButton("4"); // 数字键4
JButton five = new JButton("5"); // 数字键5
JButton six = new JButton("6"); // 数字键6
JButton seven = new JButton("7"); // 数字键7
JButton eight = new JButton("8"); // 数字键8
JButton nine = new JButton("9"); // 数字键9
JButton plus = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div = new JButton("/");
JButton equal = new JButton("=");
JButton ce = new JButton("清零"); // 置零键
JButton point = new JButton(".");
Number_Key() {
setLayout(new GridLayout(4, 4, 1, 1)); // 定义布局管理器为网格布局
setBackground(Color.blue); // 设置背景颜色
// 添加按钮
add(one);
add(two);
add(three);
add(four);
add(five);
add(six);
add(seven);
add(eight);
add(nine);
add(zero);
add(plus);
add(sub);
add(mul);
add(div);
add(point);
add(equal);
add(ce);
}
}
// 计算器显示结果的窗体
class Result extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
// text先是输入和结果
JTextField text = new JTextField("0");
@SuppressWarnings("deprecation")
Result() { // 讲输入的数字或得到的结果在text的右边显示
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.enable(false); // 文本框不能编辑
setLayout(new BorderLayout()); // 设定布局管理器边框布局
add(text, BorderLayout.CENTER); // text放置在窗体的中间
}
}
直接复制 保存成Jisuanqi .java可以直接运行了
编写计算器java
仅供参考,最好自己亲自动手写,这样才会有进步
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Jisuanqi extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
Result result = new Result(); // 定义text的面板
Number_Key number_key = new Number_Key(); // 定义按钮面板
// 当点击按钮+、-、*、/时,com = true
boolean com = false;
// 当i=0时说明是我们第一次输入,字符串text不会累加
int i = 0;
// 存放text的内容
String text = "";
// 存放点击按钮+、-、*、/之前的数值
double defbutton = 0;
// +、-、*、/的代号分别为1,2,3,4
int symbol = 0;
// 构造函数
Jisuanqi() {
super("WangJiao"); // 设定标题
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设定关闭窗体时退出程序
JPanel pane = new JPanel(); // 定义主面板
pane.setLayout(new BorderLayout());
setBounds(380, 220, 30, 80); // 前两个参数是在屏幕上显示的坐标,后两个是大小
// 替换图标
ImageIcon icon = new ImageIcon("F:1.GIF");
// Jisuanqi.class.getResource("APPLE.GIF")
// );
setIconImage(icon.getImage());
pane.add(result, BorderLayout.NORTH);
pane.add(number_key, BorderLayout.CENTER);
pane.add(number_key.equal, BorderLayout.SOUTH);
number_key.one.addActionListener(this); // 对1按钮添加监听事件
number_key.two.addActionListener(this); // 对2按钮添加监听事件
number_key.three.addActionListener(this); // 对3按钮添加监听事件
number_key.four.addActionListener(this); // 对4按钮添加监听事件
number_key.five.addActionListener(this); // 对5按钮添加监听事件
number_key.six.addActionListener(this); // 对6按钮添加监听事件
number_key.seven.addActionListener(this); // 对7按钮添加监听事件
number_key.eight.addActionListener(this); // 对8按钮添加监听事件
number_key.nine.addActionListener(this); // 对9按钮添加监听事件
number_key.zero.addActionListener(this); // 对0按钮添加监听事件
number_key.ce.addActionListener(this); // 对置零按钮添加监听事件
number_key.plus.addActionListener(this); // 对+按钮添加监听事件
number_key.equal.addActionListener(this); // 对=按钮添加监听事件
number_key.sub.addActionListener(this); // 对-按钮添加监听事件
number_key.mul.addActionListener(this); // 对*按钮添加监听事件
number_key.div.addActionListener(this); // 对/按钮添加监听事件
number_key.point.addActionListener(this); // 对.按钮添加监听事件
setContentPane(pane);
pack(); // 初始化窗体大小为正好盛放所有按钮
}
// 各个按钮触发的事件
public void actionPerformed(ActionEvent e) {
/*
* 如果是点击数字按钮那么先要判断是否在此之前点击了+、-、*、/、=,如果是那么com=true 如果没有com=
* false;或者是否点击数字键,如果是i = 1,如果没有 i = 0;
*/
if (e.getSource() == number_key.one) {
if (com || i == 0) {
result.text.setText("1");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "1");
}
} else if (e.getSource() == number_key.two) {
if (com || i == 0) {
result.text.setText("2");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "2");
}
} else if (e.getSource() == number_key.three) {
if (com || i == 0) {
result.text.setText("3");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "3");
}
} else if (e.getSource() == number_key.four) {
if (com || i == 0) {
result.text.setText("4");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "4");
}
} else if (e.getSource() == number_key.five) {
if (com || i == 0) {
result.text.setText("5");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "5");
}
} else if (e.getSource() == number_key.six) {
if (com || i == 0) {
result.text.setText("6");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "6");
}
} else if (e.getSource() == number_key.seven) {
if (com || i == 0) {
result.text.setText("7");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "7");
}
} else if (e.getSource() == number_key.eight) {
if (com || i == 0) {
result.text.setText("8");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "8");
}
} else if (e.getSource() == number_key.nine) {
if (com || i == 0) {
result.text.setText("9");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "9");
}
}
/*
* 对于0这个按钮有一定的说法,在我的程序里不会出现如00000这样的情况,我加了判断条件就是
* 如果text中的数值=0就要判断在这个数值中是否有.存在?如果有那么就在原来数值基础之上添 加0;否则保持原来的数值不变
*/
else if (e.getSource() == number_key.zero) { // result.text.getText()是得到text里内容的意思
if (com || i == 0) {
result.text.setText("0");
com = false;
i = 1;
} else {
text = result.text.getText();
if (Float.parseFloat(text) 0 || Float.parseFloat(text) 0) { // Float.parseFloat(text)就是类型转换了,下面都是一样
result.text.setText(text + "0");
} else {
if (text.trim().indexOf(".") == -1) {
result.text.setText(text);
} else {
result.text.setText(text + "0");
}
}
}
} else if (e.getSource() == number_key.ce) {
result.text.setText("0");
i = 0;
com = true;
// text = "";
defbutton = 0;
}
/*
* 本程序不会让一个数值中出现2个以上的小数点.具体做法是:判断是否已经存在.存在就不添加, 不存在就添加.
*/
else if (e.getSource() == number_key.point) {
if (com || i == 0) {
result.text.setText("0.");
com = false;
i = 1;
} else {
text = result.text.getText();
if (text.trim().indexOf(".") == -1) {
result.text.setText(text + ".");
} else {
result.text.setText(text);
}
}
} // 获得点击+之前的数值
else if (e.getSource() == number_key.plus) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 1;
} // 获得点击-之前的数值
else if (e.getSource() == number_key.sub) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 2;
} // 获得点击*之前的数值
else if (e.getSource() == number_key.mul) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
System.out.println(defbutton);
symbol = 3;
} // 获得点击/之前的数值
else if (e.getSource() == number_key.div) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 4;
} else if (e.getSource() == number_key.equal) {
switch (symbol) {
case 1: { // 计算加法
double ad = defbutton
+ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 2: { // 计算减法
double ad = defbutton
- Double.parseDouble(result.text.getText());
result.text.setText(String.valueOf(ad));
i = 0;
text = "";
break;
}
case 3: { // 计算乘法
double ad = defbutton
* Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 4: { // 计算除法
double ad = defbutton
/ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
}
System.out.println(com);
}
System.out.println(result.text.getText());
}
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Jisuanqi loveyou = new Jisuanqi();
loveyou.show();
}
}
// 计算器数字按钮定义面板
class Number_Key extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JButton zero = new JButton("0"); // 数字键0
JButton one = new JButton("1"); // 数字键1
JButton two = new JButton("2"); // 数字键2
JButton three = new JButton("3"); // 数字键3
JButton four = new JButton("4"); // 数字键4
JButton five = new JButton("5"); // 数字键5
JButton six = new JButton("6"); // 数字键6
JButton seven = new JButton("7"); // 数字键7
JButton eight = new JButton("8"); // 数字键8
JButton nine = new JButton("9"); // 数字键9
JButton plus = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div = new JButton("/");
JButton equal = new JButton("=");
JButton ce = new JButton("清零"); // 置零键
JButton point = new JButton(".");
Number_Key() {
setLayout(new GridLayout(4, 4, 1, 1)); // 定义布局管理器为网格布局
setBackground(Color.blue); // 设置背景颜色
// 添加按钮
add(one);
add(two);
add(three);
add(four);
add(five);
add(six);
add(seven);
add(eight);
add(nine);
add(zero);
add(plus);
add(sub);
add(mul);
add(div);
add(point);
add(equal);
add(ce);
}
}
// 计算器显示结果的窗体
class Result extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
// text先是输入和结果
JTextField text = new JTextField("0");
@SuppressWarnings("deprecation")
Result() { // 讲输入的数字或得到的结果在text的右边显示
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.enable(false); // 文本框不能编辑
setLayout(new BorderLayout()); // 设定布局管理器边框布局
add(text, BorderLayout.CENTER); // text放置在窗体的中间
}
}