‘壹’ 使用java类描述一个计算器类 计算器具备操作数1, 操作数2 ,还具备计算的功能行为。
//给你给之前我些的代码
//封装两个数
publicclassComputer{
privatedoublenum1;
privatedoublenum2;
publicComputer(){
}
publicComputer(doublenum1,doublenum2){
this.num1=num1;
this.num2=num2;
}
publicdoublegetNum1(){
returnnum1;
}
publicvoidsetNum1(doublenum1){
this.num1=num1;
}
publicdoublegetNum2(){
returnnum2;
}
publicvoidsetNum2(doublenum2){
this.num2=num2;
}
}
//封装加法运算
publicclassSum{
publicdoublemethod(Computercom){
returncom.getNum1()+com.getNum2();
}
}
//封装减法运算
publicclassSubtraction{
publicdoublemethod(Computercom){
returncom.getNum1()-com.getNum2();
}
}
//封装乘法运算
publicclassProct{
publicdoublemethod(Computercom){
returncom.getNum1()*com.getNum2();
}
}
//封装除法运算
publicclassDivide{
publicdoublemethod(Computercom){
returncom.getNum1()/com.getNum2();
}
}
//封装运算过程
publicclassComputerFactry{
publicdoublemethod(intoption,doublenum1,doublenum2){
doublenumber=0;
Computercom=newComputer(num1,num2);
switch(option){
case1:
number=newSum().method(com);
break;
case2:
number=newSubtraction().method(com);
break;
case3:
number=newProct().method(com);
break;
case4:
number=newDivide().method(com);
break;
}
returnnumber;
}
}
//程序界面
importjava.util.Scanner;
publicclassDemo{
publicstaticvoidmain(String[]args){
doublenum1=0,num2=0;
intoption=0;
Scannersca=newScanner(System.in);
ComputerFactrycf=newComputerFactry();
System.out.println(" "+"=====欢迎使用计算器=====");
System.out.println("1,加法运算(+)");
System.out.println("2,减法运算(-)");
System.out.println("3,乘法运算(×)");
System.out.println("4,除法运算(÷)");
System.out.print("请选择运算方法:");
option=sca.nextInt();
System.out.print("请输入第一个数:");
num1=sca.nextDouble();
System.out.print("请输入第二个数:");
num2=sca.nextDouble();
System.out.println(cf.method(option,num1,num2));
}
}
‘贰’ java实现计算器的程序
///你运行看看,效果绝对让你满意!呵呵……
///////
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import javax.swing.*;
public class Counter extends Frame
{
//声明三个面板的布局
GridLayout gl1,gl2,gl3;
Panel p0,p1,p2,p3;
JTextField tf1;
TextField tf2;
Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25,b26;
StringBuffer str;//显示屏所显示的字符串
double x,y;//x和y都是运算数
int z;//Z表示单击了那一个运算符.0表示"+",1表示"-",2表示"*",3表示"/"
static double m;//记忆的数字
public Counter()
{
gl1=new GridLayout(1,4,10,0);//实例化三个面板的布局
gl2=new GridLayout(4,1,0,15);
gl3=new GridLayout(4,5,10,15);
tf1=new JTextField(27);//显示屏
tf1.setHorizontalAlignment(JTextField.RIGHT);
tf1.setEnabled(false);
tf1.setText("0");
tf2=new TextField(10);//显示记忆的索引值
tf2.setEditable(false);
//实例化所有按钮、设置其前景色并注册监听器
b0=new Button("Backspace");
b0.setForeground(Color.red);
b0.addActionListener(new Bt());
b1=new Button("CE");
b1.setForeground(Color.red);
b1.addActionListener(new Bt());
b2=new Button("C");
b2.setForeground(Color.red);
b2.addActionListener(new Bt());
b3=new Button("MC");
b3.setForeground(Color.red);
b3.addActionListener(new Bt());
b4=new Button("MR");
b4.setForeground(Color.red);
b4.addActionListener(new Bt());
b5=new Button("MS");
b5.setForeground(Color.red);
b5.addActionListener(new Bt());
b6=new Button("M+");
b6.setForeground(Color.red);
b6.addActionListener(new Bt());
b7=new Button("7");
b7.setForeground(Color.blue);
b7.addActionListener(new Bt());
b8=new Button("8");
b8.setForeground(Color.blue);
b8.addActionListener(new Bt());
b9=new Button("9");
b9.setForeground(Color.blue);
b9.addActionListener(new Bt());
b10=new Button("/");
b10.setForeground(Color.red);
b10.addActionListener(new Bt());
b11=new Button("sqrt");
b11.setForeground(Color.blue);
b11.addActionListener(new Bt());
b12=new Button("4");
b12.setForeground(Color.blue);
b12.addActionListener(new Bt());
b13=new Button("5");
b13.setForeground(Color.blue);
b13.addActionListener(new Bt());
b14=new Button("6");
b14.setForeground(Color.blue);
b14.addActionListener(new Bt());
b15=new Button("*");
b15.setForeground(Color.red);
b15.addActionListener(new Bt());
b16=new Button("%");
b16.setForeground(Color.blue);
b16.addActionListener(new Bt());
b17=new Button("1");
b17.setForeground(Color.blue);
b17.addActionListener(new Bt());
b18=new Button("2");
b18.setForeground(Color.blue);
b18.addActionListener(new Bt());
b19=new Button("3");
b19.setForeground(Color.blue);
b19.addActionListener(new Bt());
b20=new Button("-");
b20.setForeground(Color.red);
b20.addActionListener(new Bt());
b21=new Button("1/X");
b21.setForeground(Color.blue);
b21.addActionListener(new Bt());
b22=new Button("0");
b22.setForeground(Color.blue);
b22.addActionListener(new Bt());
b23=new Button("+/-");
b23.setForeground(Color.blue);
b23.addActionListener(new Bt());
b24=new Button(".");
b24.setForeground(Color.blue);
b24.addActionListener(new Bt());
b25=new Button("+");
b25.setForeground(Color.red);
b25.addActionListener(new Bt());
b26=new Button("=");
b26.setForeground(Color.red);
b26.addActionListener(new Bt());
//实例化四个面板
p0=new Panel();
p1=new Panel();
p2=new Panel();
p3=new Panel();
//创建一个空字符串缓冲区
str=new StringBuffer();
//添加面板p0中的组件和设置其在框架中的位置和大小
p0.add(tf1);
p0.setBounds(10,25,300,40);
//添加面板p1中的组件和设置其在框架中的位置和大小
p1.setLayout(gl1);
p1.add(tf2);
p1.add(b0);
p1.add(b1);
p1.add(b2);
p1.setBounds(10,65,300,25);
//添加面板p2中的组件并设置其的框架中的位置和大小
p2.setLayout(gl2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.setBounds(10,110,40,150);
//添加面板p3中的组件并设置其在框架中的位置和大小
p3.setLayout(gl3);//设置p3的布局
p3.add(b7);
p3.add(b8);
p3.add(b9);
p3.add(b10);
p3.add(b11);
p3.add(b12);
p3.add(b13);
p3.add(b14);
p3.add(b15);
p3.add(b16);
p3.add(b17);
p3.add(b18);
p3.add(b19);
p3.add(b20);
p3.add(b21);
p3.add(b22);
p3.add(b23);
p3.add(b24);
p3.add(b25);
p3.add(b26);
p3.setBounds(60,110,250,150);
//设置框架中的布局为空布局并添加4个面板
setLayout(null);
add(p0);
add(p1);
add(p2);
add(p3);
setResizable(false);//禁止调整框架的大小
//匿名类关闭窗口
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e1)
{
System.exit(0);
}
});
setBackground(Color.lightGray);
setBounds(100,100,320,280);
setVisible(true);
}
//构造监听器
class Bt implements ActionListener
{
public void actionPerformed(ActionEvent e2)
{
try{
if(e2.getSource()==b1)//选择"CE"清零
{
tf1.setText("0");//把显示屏清零
str.setLength(0);//清空字符串缓冲区以准备接收新的输入运算数
}
else if(e2.getSource()==b2)//选择"C"清零
{
tf1.setText("0");//把显示屏清零
str.setLength(0);
}
else if(e2.getSource()==b23)//单击"+/-"选择输入的运算数是正数还是负数
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText(""+(-x));
}
else if(e2.getSource()==b25)//单击加号按钮获得x的值和z的值并清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);//清空缓冲区以便接收新的另一个运算数
y=0d;
z=0;
}
else if(e2.getSource()==b20)//单击减号按钮获得x的值和z的值并清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=1;
}
else if(e2.getSource()==b15)//单击乘号按钮获得x的值和z的值并清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=2;
}
else if(e2.getSource()==b10)//单击除号按钮获得x的值和z的值并空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=3;
}
else if(e2.getSource()==b26)//单击等号按钮输出计算结果
{
str.setLength(0);
switch(z)
{
case 0 : tf1.setText(""+(x+y));break;
case 1 : tf1.setText(""+(x-y));break;
case 2 : tf1.setText(""+(x*y));break;
case 3 : tf1.setText(""+(x/y));break;
}
}
else if(e2.getSource()==b24)//单击"."按钮输入小数
{
if(tf1.getText().trim().indexOf(".")!=-1)//判断字符串中是否已经包含了小数点
{
}
else//如果没数点有小
{
if(tf1.getText().trim().equals("0"))//如果初时显示为0
{
str.setLength(0);
tf1.setText((str.append("0"+e2.getActionCommand())).toString());
}
else if(tf1.getText().trim().equals(""))//如果初时显示为空则不做任何操作
{
}
else
{
tf1.setText(str.append(e2.getActionCommand()).toString());
}
}
y=0d;
}
else if(e2.getSource()==b11)//求平方根
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText("数字格式异常");
if(x<0)
tf1.setText("负数没有平方根");
else
tf1.setText(""+Math.sqrt(x));
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b16)//单击了"%"按钮
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText(""+(0.01*x));
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b21)//单击了"1/X"按钮
{
x=Double.parseDouble(tf1.getText().trim());
if(x==0)
{
tf1.setText("除数不能为零");
}
else
{
tf1.setText(""+(1/x));
}
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b3)//MC为清除内存
{
m=0d;
tf2.setText("");
str.setLength(0);
}
else if(e2.getSource()==b4)//MR为重新调用存储的数据
{
if(tf2.getText().trim()!="")//有记忆数字
{
tf1.setText(""+m);
}
}
else if(e2.getSource()==b5)//MS为存储显示的数据
{
m=Double.parseDouble(tf1.getText().trim());
tf2.setText("M");
tf1.setText("0");
str.setLength(0);
}
else if(e2.getSource()==b6)//M+为将显示的数字与已经存储的数据相加要查看新的数字单击MR
{
m=m+Double.parseDouble(tf1.getText().trim());
}
else//选择的是其他的按钮
{
if(e2.getSource()==b22)//如果选择的是"0"这个数字键
{
if(tf1.getText().trim().equals("0"))//如果显示屏显示的为零不做操作
{
}
else
{
tf1.setText(str.append(e2.getActionCommand()).toString());
y=Double.parseDouble(tf1.getText().trim());
}
}
else if(e2.getSource()==b0)//选择的是“BackSpace”按钮
{
if(!tf1.getText().trim().equals("0"))//如果显示屏显示的不是零
{
if(str.length()!=1)
{
tf1.setText(str.delete(str.length()-1,str.length()).toString());//可能抛出字符串越界异常
}
else
{
tf1.setText("0");
str.setLength(0);
}
}
y=Double.parseDouble(tf1.getText().trim());
}
else//其他的数字键
{
tf1.setText(str.append(e2.getActionCommand()).toString());
y=Double.parseDouble(tf1.getText().trim());
}
}
}
catch(NumberFormatException e){
tf1.setText("数字格式异常");
}
catch( e){
tf1.setText("字符串索引越界");
}
}
}
public static void main(String args[])
{
new Counter();
}
}
‘叁’ JAVA带括号计算器
我以前做过一个,不过不记得了,讲一下思路吧:
你可以用一个栈来存放数据,再用一个栈来存放符号,然后就是解析你输入的表达式了,遇到数字就进栈,遇到运算符的话就从数字栈中出栈两个数字进行相应的运算......
‘肆’ 用Java编写一个计算器,实现+,-,*,/,%,++,--的计算操作.不用太复杂
publicstaticvoidmain(String[]args){
intone=1;
inttwo=2;
Stringmark="--";
calc(one,mark,two);//如果为递加或递减的情况,请注意传参顺序
}
publicstaticvoidcalc(intone,Stringmark,inttwo){
intresult=0;
switch(mark){
case"+":
result=one+two;
break;
case"-":
result=one-two;
break;
case"*":
result=one*two;
break;
case"/":
result=one/two;
break;
case"%":
result=one%two;
break;
case"++":
result=++one;
break;
case"--":
result=--one;
break;
default:
break;
}
System.out.println(result);
}
‘伍’ 怎么用java做一个带括号的计算器
importjava.awt.*;
importjava.awt.event.*;
publicclassMyCalculator{
privateFramef;
privateTextFieldtf=newTextField(30);
privatelongresult;
privatebooleanappend=false;
privatecharoperator='=';
privateButton[]btn=newButton[15];
publicMyCalculator(){
initComponent();
}
privatevoidinitComponent(){
f=newFrame("MyCalculatorV1.0");
f.setLayout(newBorderLayout());//TheframeusesBorderLayout
f.addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEventevt){
System.exit(0);
}
});
PanelcenterPanel=newPanel();
centerPanel.setLayout(newGridLayout(5,3));//ThepanelusesGridLayout
NumberListenernl=newNumberListener();
OperatorListenerol=newOperatorListener();
btn[10]=newButton("+");
btn[11]=newButton("-");
btn[12]=newButton("*");
btn[13]=newButton("/");
btn[14]=newButton("=");
for(inti=0;i<=9;i++){
btn[i]=newButton(String.valueOf(i));
centerPanel.add(btn[i]);
btn[i].addActionListener(nl);
if(i%2==1){
centerPanel.add(btn[(i+19)/2]);
btn[(i+19)/2].addActionListener(ol);
}
}
f.add(centerPanel,BorderLayout.CENTER);
PanelnorthPanel=newPanel();
tf.setEditable(false);
northPanel.add(tf);
f.add(northPanel,BorderLayout.NORTH);
}
publicvoidgo(){
f.pack();
f.setVisible(true);
}
publicstaticvoidmain(String[]args){
newMyCalculator().go();
}
/**
*采用成员内部类方式,实现监听器接口,方便访问主类内类内部成员。
*此类负责数字按钮Action事件监听和处理
*/
{
publicvoidactionPerformed(ActionEvente){
if(!append){
tf.setText("");
append=true;
}
Strings=tf.getText();
s+=e.getActionCommand();
tf.setText(s);
if(!btn[10].isEnabled()){
for(inti=10;i<=14;i++)btn[i].setEnabled(true);
}
}
}
/**
*成员内部类,负责操作符按钮的事件处理
*/
{
publicvoidactionPerformed(ActionEvente){
if(!append)return;
for(inti=10;i<=14;i++)btn[i].setEnabled(false);
Strings=tf.getText();
longnum=Long.parseLong(s);//getthenumberoftextfield
append=false;//setappend
switch(operator){
case'+':result+=num;break;
case'-':result-=num;break;
case'*':result*=num;break;
case'/':{
if(num==0)result=0;
elseresult/=num;
break;
}
case'=':result=num;break;
}
tf.setText(String.valueOf(result));
//
Stringop=e.getActionCommand();
operator=op.charAt(0);//setoperator
}
}
}
‘陆’ java实现复杂计算器
importjava.util.Scanner;
importjavax.script.ScriptEngine;
importjavax.script.ScriptEngineManager;
importjavax.script.ScriptException;
publicclassKyo
{
publicstaticvoidmain(String[]args)
{
ScriptEngineManagersem=newScriptEngineManager();
ScriptEnginese=sem.getEngineByName("js");
Scannerscan=newScanner(System.in);
while(true)
{
System.out.println("输入一个式子:");
Stringjsonstr=scan.nextLine().trim();
try
{
doubled=Double.parseDouble(se.eval("("+jsonstr+")").toString());
System.out.printf("%s=%.1f%n",jsonstr,d);
}
catch(ScriptExceptione)
{
System.err.println("输入的式子不合法,退出程序");
scan.close();
break;
}
}
}
}
‘柒’ java如何在计算器中加入小括号功能
这个不就看你的程序怎么写了吗?你可以把用户输入的先保存下来,用户按等于的时候,你的程序区解析你保存下来的东西,不就等于加入了小括号了,怎么解析就看你要什么需求了,祝你成功
‘捌’ 求简单计算器JAVA编程
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame {
private Container container;
private GridBagLayout layout;
private GridBagConstraints constraints;
private JTextField displayField;// 计算结果显示区
private String lastCommand;// 保存+,-,*,/,=命令
private double result;// 保存计算结果
private boolean start;// 判断是否为数字的开始
public Calculator() {
super("Calculator");
container = getContentPane();
layout = new GridBagLayout();
container.setLayout(layout);
constraints = new GridBagConstraints();
start = true;
result = 0;
lastCommand = "=";
displayField = new JTextField(20);
displayField.setHorizontalAlignment(JTextField.RIGHT);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 4;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 100;
constraints.weighty = 100;
layout.setConstraints(displayField, constraints);
container.add(displayField);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
// addButton("Backspace", 0, 1, 2, 1, insert);
// addButton("CE", 2, 1, 1, 1, insert);
// addButton("C", 3, 1, 1, 1, insert);
addButton("7", 0, 2, 1, 1, insert);
addButton("8", 1, 2, 1, 1, insert);
addButton("9", 2, 2, 1, 1, insert);
addButton("/", 3, 2, 1, 1, command);
addButton("4", 0, 3, 1, 1, insert);
addButton("5", 1, 3, 1, 1, insert);
addButton("6", 2, 3, 1, 1, insert);
addButton("*", 3, 3, 1, 1, command);
addButton("1", 0, 4, 1, 1, insert);
addButton("2", 1, 4, 1, 1, insert);
addButton("3", 2, 4, 1, 1, insert);
addButton("-", 3, 4, 1, 1, command);
addButton("0", 0, 5, 1, 1, insert);
// addButton("+/-", 1, 5, 1, 1, insert);// 只显示"-"号,"+"没有实用价值
addButton(".", 2, 5, 1, 1, insert);
addButton("+", 3, 5, 1, 1, command);
addButton("=", 0, 6, 4, 1, command);
this.setResizable(false);
setSize(180, 200);
setVisible(true);
}
private void addButton(String label, int row, int column, int with,
int height, ActionListener listener) {
JButton button = new JButton(label);
constraints.gridx = row;
constraints.gridy = column;
constraints.gridwidth = with;
constraints.gridheight = height;
constraints.fill = GridBagConstraints.BOTH;
button.addActionListener(listener);
layout.setConstraints(button, constraints);
container.add(button);
}
private class InsertAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (start) {
displayField.setText("");
start = false;
if (input.equals("+/-"))
displayField.setText(displayField.getText() + "-");
}
if (!input.equals("+/-")) {
if (input.equals("Backspace")) {
String str = displayField.getText();
if (str.length() > 0)
displayField
.setText(str.substring(0, str.length() - 1));
} else if (input.equals("CE") || input.equals("C")) {
displayField.setText("0");
start = true;
} else
displayField.setText(displayField.getText() + input);
}
}
}
private class CommandAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String command = evt.getActionCommand();
if (start) {
lastCommand = command;
} else {
calculate(Double.parseDouble(displayField.getText()));
lastCommand = command;
start = true;
}
}
}
public void calculate(double x) {
if (lastCommand.equals("+"))
result += x;
else if (lastCommand.equals("-"))
result -= x;
else if (lastCommand.equals("*"))
result *= x;
else if (lastCommand.equals("/"))
result /= x;
else if (lastCommand.equals("="))
result = x;
displayField.setText("" + result);
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
‘玖’ 用java设计一个计算器 1.可以没有界面,但要有输入和输出 2.整数,小数,加减乘除,求余,括号
package com.electricauto.work.controller;
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.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* 一个计算器,与Windows附件自带计算器的标准版功能、界面相仿。 但还不支持键盘操作。
*/
public class jisuanqi extends JFrame implements ActionListener {
/** 计算器上的键的显示名字 */
private final String[] KEYS = { "7", "8", "9", "/", "sqrt", "4", "5", "6",
"*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };
/** 计算器上的功能键的显示名字 */
private final String[] COMMAND = { "Backspace", "CE", "C" };
/** 计算器左边的M的显示名字 */
private final String[] M = { " ", "MC", "MR", "MS", "M+" };
/** 计算器上键的按钮 */
private JButton keys[] = new JButton[KEYS.length];
/** 计算器上的功能键的按钮 */
private JButton commands[] = new JButton[COMMAND.length];
/** 计算器左边的M的按钮 */
private JButton m[] = new JButton[M.length];
/** 计算结果文本框 */
private JTextField resultText = new JTextField("0");
// 标志用户按的是否是整个表达式的第一个数字,或者是运算符后的第一个数字
private boolean firstDigit = true;
// 计算的中间结果。
private double resultNum = 0.0;
// 当前运算的运算符
private String operator = "=";
// 操作是否合法
private boolean operateValidFlag = true;
/**
* 构造函数
*/
public jisuanqi() {
super();
// 初始化计算器
init();
// 设置计算器的背景颜色
this.setBackground(Color.LIGHT_GRAY);
this.setTitle("计算器");
// 在屏幕(500, 300)坐标处显示计算器
this.setLocation(500, 300);
// 不许修改计算器的大小
this.setResizable(false);
// 使计算器中各组件大小合适
this.pack();
}
/**
* 初始化计算器
*/
private void init() {
// 文本框中的内容采用右对齐方式
resultText.setHorizontalAlignment(JTextField.RIGHT);
// 不允许修改结果文本框
resultText.setEditable(false);
// 设置文本框背景颜色为白色
resultText.setBackground(Color.white);
// 初始化计算器上键的按钮,将键放在一个画板内
JPanel calckeysPanel = new JPanel();
// 用网格布局器,4行,5列的网格,网格之间的水平方向间隔为3个象素,垂直方向间隔为3个象素
calckeysPanel.setLayout(new GridLayout(4, 5, 3, 3));
for (int i = 0; i < KEYS.length; i++) {
keys[i] = new JButton(KEYS[i]);
calckeysPanel.add(keys[i]);
keys[i].setForeground(Color.blue);
}
// 运算符键用红色标示,其他键用蓝色表示
keys[3].setForeground(Color.red);
keys[8].setForeground(Color.red);
keys[13].setForeground(Color.red);
keys[18].setForeground(Color.red);
keys[19].setForeground(Color.red);
// 初始化功能键,都用红色标示。将功能键放在一个画板内
JPanel commandsPanel = new JPanel();
// 用网格布局器,1行,3列的网格,网格之间的水平方向间隔为3个象素,垂直方向间隔为3个象素
commandsPanel.setLayout(new GridLayout(1, 3, 3, 3));
for (int i = 0; i < COMMAND.length; i++) {
commands[i] = new JButton(COMMAND[i]);
commandsPanel.add(commands[i]);
commands[i].setForeground(Color.red);
}
// 初始化M键,用红色标示,将M键放在一个画板内
JPanel calmsPanel = new JPanel();
// 用网格布局管理器,5行,1列的网格,网格之间的水平方向间隔为3个象素,垂直方向间隔为3个象素
calmsPanel.setLayout(new GridLayout(5, 1, 3, 3));
for (int i = 0; i < M.length; i++) {
m[i] = new JButton(M[i]);
calmsPanel.add(m[i]);
m[i].setForeground(Color.red);
}
// 下面进行计算器的整体布局,将calckeys和command画板放在计算器的中部,
// 将文本框放在北部,将calms画板放在计算器的西部。
// 新建一个大的画板,将上面建立的command和calckeys画板放在该画板内
JPanel panel1 = new JPanel();
// 画板采用边界布局管理器,画板里组件之间的水平和垂直方向上间隔都为3象素
panel1.setLayout(new BorderLayout(3, 3));
panel1.add("North", commandsPanel);
panel1.add("West", calckeysPanel);
// 建立一个画板放文本框
JPanel top = new JPanel();
top.setLayout(new BorderLayout());
top.add("Center", resultText);
// 整体布局
getContentPane().setLayout(new BorderLayout(3, 5));
getContentPane().add("North", top);
getContentPane().add("Center", panel1);
getContentPane().add("West", calmsPanel);
// 为各按钮添加事件侦听器
// 都使用同一个事件侦听器,即本对象。本类的声明中有implements ActionListener
for (int i = 0; i < KEYS.length; i++) {
keys[i].addActionListener(this);
}
for (int i = 0; i < COMMAND.length; i++) {
commands[i].addActionListener(this);
}
for (int i = 0; i < M.length; i++) {
m[i].addActionListener(this);
}
}
/**
* 处理事件
*/
public void actionPerformed(ActionEvent e) {
// 获取事件源的标签
String label = e.getActionCommand();
if (label.equals(COMMAND[0])) {
// 用户按了"Backspace"键
handleBackspace();
} else if (label.equals(COMMAND[1])) {
// 用户按了"CE"键
resultText.setText("0");
} else if (label.equals(COMMAND[2])) {
// 用户按了"C"键
handleC();
} else if ("0123456789.".indexOf(label) >= 0) {
// 用户按了数字键或者小数点键
handleNumber(label);
// handlezero(zero);
} else {
// 用户按了运算符键
handleOperator(label);
}
}
/**
* 处理Backspace键被按下的事件
*/
private void handleBackspace() {
String text = resultText.getText();
int i = text.length();
if (i > 0) {
// 退格,将文本最后一个字符去掉
text = text.substring(0, i - 1);
if (text.length() == 0) {
// 如果文本没有了内容,则初始化计算器的各种值
resultText.setText("0");
firstDigit = true;
operator = "=";
} else {
// 显示新的文本
resultText.setText(text);
}
}
}
/**
* 处理数字键被按下的事件
*
* @param key
*/
private void handleNumber(String key) {
if (firstDigit) {
// 输入的第一个数字
resultText.setText(key);
} else if ((key.equals(".")) && (resultText.getText().indexOf(".") < 0)) {
// 输入的是小数点,并且之前没有小数点,则将小数点附在结果文本框的后面
resultText.setText(resultText.getText() + ".");
} else if (!key.equals(".")) {
// 如果输入的不是小数点,则将数字附在结果文本框的后面
resultText.setText(resultText.getText() + key);
}
// 以后输入的肯定不是第一个数字了
firstDigit = false;
}
/**
* 处理C键被按下的事件
*/
private void handleC() {
// 初始化计算器的各种值
resultText.setText("0");
firstDigit = true;
operator = "=";
}
/**
* 处理运算符键被按下的事件
*
* @param key
*/
private void handleOperator(String key) {
if (operator.equals("/")) {
// 除法运算
// 如果当前结果文本框中的值等于0
if (getNumberFromText() == 0.0) {
// 操作不合法
operateValidFlag = false;
resultText.setText("除数不能为零");
} else {
resultNum /= getNumberFromText();
}
} else if (operator.equals("1/x")) {
// 倒数运算
if (resultNum == 0.0) {
// 操作不合法
operateValidFlag = false;
resultText.setText("零没有倒数");
} else {
resultNum = 1 / resultNum;
}
} else if (operator.equals("+")) {
// 加法运算
resultNum += getNumberFromText();
} else if (operator.equals("-")) {
// 减法运算
resultNum -= getNumberFromText();
} else if (operator.equals("*")) {
// 乘法运算
resultNum *= getNumberFromText();
} else if (operator.equals("sqrt")) {
// 平方根运算
resultNum = Math.sqrt(resultNum);
} else if (operator.equals("%")) {
// 百分号运算,除以100
resultNum = resultNum / 100;
} else if (operator.equals("+/-")) {
// 正数负数运算
resultNum = resultNum * (-1);
} else if (operator.equals("=")) {
// 赋值运算
resultNum = getNumberFromText();
}
if (operateValidFlag) {
// 双精度浮点数的运算
long t1;
double t2;
t1 = (long) resultNum;
t2 = resultNum - t1;
if (t2 == 0) {
resultText.setText(String.valueOf(t1));
} else {
resultText.setText(String.valueOf(resultNum));
}
}
// 运算符等于用户按的按钮
operator = key;
firstDigit = true;//这个地方太tm巧妙了想好几天, 先进行上一次操作,再将本次操作(最后一次操作)赋给操作,所以每次操作前都先进行上一次操作,默认操作为"=" 挺nb
operateValidFlag = true;
}
/**
* 从结果文本框中获取数字
*
* @return
*/
private double getNumberFromText() {
double result = 0;
try {
result = Double.valueOf(resultText.getText()).doubleValue(); //显示文字后不会蹦出
} catch (NumberFormatException e) {
}
return result;
}
public static void main(String args[]) {
jisuanqi calculator1 = new jisuanqi();
calculator1.setVisible(true);
calculator1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
========================================================
代码比较多,放在任何一个项目里都行,新建一个叫做 jisuanqi 的java文件,粘贴进去就行,会有一个错误是包位置的选择,点击错误选择正确的包位置就可以了, 无错误后执行文件最下面的main函数,就会出现计算器。有不懂的可以继续问,望采纳~!