网站首页 > 文章中心 > 其它

计算器编程代码java

作者:小编 更新时间:2023-08-29 23:33:08 浏览量:382人看过

求用JAVA实现计算器的代码(可实用的,没语法错误的)

计算器 用java编写

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

计算器编程代码java-图1

import java.math.BigDecimal;

import javax.swing.*;

public class TestComputer implements ActionListener{//用于接收操作事件的侦听器接口.对处理操作事件感兴趣的类可以实现此接口,

//而使用该类创建的对象可使用组件的 addActionListener 方法向该组件注册.在发生操作事件时,调用该对象的 actionPerformed 方法.

private boolean append = false;//数字处于替换状态

JTextField jtf = new JTextField(10);//构造一个具有指定列数的新的空 TextField.

private String operator = "+";

private String op1 = "0";

public void actionPerformed(ActionEvent ae){//发生操作时调用.

String com = ae.getActionCommand();//返回与此动作相关的命令字符串.

计算器编程代码java-图2

if(append){//追加

String temp = jtf.getText();//返回此 TextComponent 中包含的文本.

jtf.setText(temp+com);//将此 TextComponent 文本设置为指定文本.

}else{//替换

jtf.setText(com);

append = true;

}

}else if("+-*/".indexOf(com)!=-1){//返回第一次出现的指定子字符串在此字符串中的索引.

op1 = jtf.getText();

operator = com;

append = false;

}else if("=".equals(com)){

BigDecimal d1 = new BigDecimal(op1);// 将 BigDecimal 的字符串表示形式转换为 BigDecimal.

if("+".equals(operator)){

}else if("-".equals(operator)){

}else if("*".equals(operator)){

}else{

jtf.setText(d1.toString());//返回此 BigDecimal 的字符串表示形式,如果需要指数,则使用科学记数法.

}else if(".".equals(com)){

String temp = jtf.getText();

if(temp.indexOf(com)==-1){//没有找到

jtf.setText(temp+".");

}else if("+/-".equals(com)){

if(temp.startsWith("-")){

jtf.setText(temp.substring(1));

jtf.setText("-"+temp);

}else if("Back".equals(com)){

if(temp.length()0){

jtf.setText(temp.substring(0,temp.length()-1));

}else if("CE".equals(com)||"C".equals(com)){

jtf.setText("0");

public TestComputer(){

JFrame jf = new JFrame("grefr的计算器");//创建一个新的、初始不可见的、具有指定标题的 Frame.

JPanel jp = new JPanel();//创建具有双缓冲和流布局的新 JPanel.

//setLayout(LayoutManager mgr)设置此容器的布局管理器.

//GridLayout(int rows, int cols)创建具有指定行数和列数的网格布局.

JButton[] jb = new JButton[lab.length];

jf.add(jtf,BorderLayout.NORTH);

for(int i=0;ijb.length;i++){

jb[i] = new JButton(lab[i]);

jp.add(jb[i]);

jb[i].addActionListener(this);//将一个 ActionListener 添加到按钮中.

jf.add(jp);

jf.setVisible(true);

jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String[] args) {

new TestComputer();

计算器java代码

import java.awt.Color;

import java.awt.Font;

import java.awt.GridLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.WindowConstants;

import javax.swing.border.LineBorder;

class Normal{

double i,j;

i=num1;

public double puls(){

return i+j;

public double subtract(){

return i-j;

public double multiply(){

return i*j;

return i/j;

public double surpuls(){

return i%j;

class scientific extends Normal{

public class calc extends JFrame{

viewNormal VN= new viewNormal("normal");

class viewNormal extends JFrame implements ActionListener{

JLabel jl;

JButton[] jb;

JButton jbs,jbo,jba,jbb,jbc,jby;

StringBuffer sb = new StringBuffer();

Normal normal;

int dot=0;

double fnum=0;

double lnum=0;

double result;

String sign=null;

public viewNormal(String title){

setTitle(title);

setLayout(null);

setVisible(true);

setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

jb[i]=new JButton(""+(i+1));

jp1.add(jb[i]);

jb[i].addActionListener(this);

jb[10]=new JButton("0");

jb[11]=new JButton("=");

jb[10].addActionListener(this);

jb[11].addActionListener(this);

jp1.add(jb[10]);

jp1.add(jb[11]);

jbs= new JButton("+");jbo= new JButton("-");jba= new JButton("*");

jbb= new JButton("/");jby= new JButton("%");jbc= new JButton("C");

jbs.addActionListener(this);jbo.addActionListener(this);jba.addActionListener(this);

jbb.addActionListener(this);jby.addActionListener(this);jbc.addActionListener(this);

jl= new JLabel("0",JLabel.RIGHT);

jl.setBackground(Color.white);

jl.setOpaque(true);

add(jl);

add(jp1);

//+

public void sum(){

lnum=Double.parseDouble(sb.toString());

normal=new Normal(fnum,lnum);

fnum=normal.puls();

result=fnum;

//-

private void sub() {

System.out.println(sb.toString());

计算器编程代码java-图3

fnum=normal.subtract();

//*

private void mul() {

fnum=normal.multiply();

// /

//%

private void sur() {

fnum=normal.surpuls();

// =

private void same(){

if(sign.equals("+")){

sum();

if(sign.equals("-")){

sub();

if(sign.equals("*")){

mul();

if(sign.equals("/")){

if(sign.equals("%")){

sur();

//result

public void Result(){

if(result%1!=0)

jl.setText(""+result);

else

{

int i=(int)result;

jl.setText(""+i);

@Override

public void actionPerformed(ActionEvent e) {

//System.out.println(sb.toString());

if(e.getSource()==jb[i]!sb.toString().equals("0")){

sb.append(jb[i].getText());

jl.setText(sb.toString());

else if(e.getSource()==jb[i]sb.toString().equals("0")){

int d=sb.length();

sb.delete(0, d);

// 0

if(e.getSource()==jb[10]!sb.toString().equals("0")){

sb.append(jb[10].getText());

// .

dot++;

// =

if(e.getSource()==jb[11]!sb.toString().equals("")){

same();

Result();

dot=0;

// +

if(e.getSource()==jbs!sb.toString().equals("")){

if(sign!="+"sign!=null)

sign ="+";

if(e.getSource()==jbo!sb.toString().equals("")){

if(fnum==0)

if(sign!="-"sign!=null)

sign ="-";

if(e.getSource()==jba!sb.toString().equals("")){

fnum=1;

if(sign!="*"sign!=null)

sign ="*";

// /

if(e.getSource()==jbb!sb.toString().equals("")){

if(sign!="/"sign!=null)

sign ="/";

// if(e.getSource()==jby!sb.toString().equals("")){

// if(fnum==0){

// fnum=Double.parseDouble(sb.toString());

// result=fnum;

// }

// else {

// if(sign!="%"sign!=null)

// same();

// else{

// lnum=Double.parseDouble(sb.toString());

// normal=new Normal(fnum,lnum);

// fnum=normal.surpuls();

// }

// sign ="%";

// Result();

// int d=sb.length();

// sb.delete(0, d);

// dot=0;

// }

//clear

if(e.getSource()==jbc){

jl.setText("0");

fnum=0;

lnum=0;

sign=null;

class viewScientific extends viewNormal{

public viewScientific(String title){

super(title);

//等号以后输入符号用不了, String转 double 本来就有错误,你可以用我的扩展成科学型的.

JAVA 编写计算器 要代码最简单的

学java的时候自己编的,很简单,能够连续输入计算式后进行计算

import java.awt.BorderLayout;

import java.awt.FlowLayout;

import java.text.NumberFormat;

import java.util.ArrayList;

/**简易计算器,能够进行简单的计算

*

*/

public class CalculatorA

implements ActionListener{

private JFrame frame;

private JTextField field;

private JButton[] allButtons;

private JButton clearButton;

// private JButton backButton;

String result="";//保存结果

StringBuilder sb = new StringBuilder();//保存要进行的计算式

int x = 0; //用来判断上一次的事件类型

ArrayListString arrayList = new ArrayListString();//保存计算式,通过方法进行运算

public CalculatorA(){

frame = new JFrame("我的计算器v1.1");

for(int i=0;iallButtons.length;i++){

allButtons[i]= new JButton(str.substring(i,i+1));

clearButton = new JButton("CLEAR");

// backButton = new JButton("——");

init();

setFondAndColor();

addEventHander();

public void init(){

frame.setLayout(new BorderLayout());

JPanel northPanel = new JPanel();

JPanel centerPanel = new JPanel();

JPanel southPanel = new JPanel();

northPanel.setLayout(new FlowLayout());

southPanel.setLayout(new FlowLayout());

northPanel.add(field);

centerPanel.add(allButtons[i]);

southPanel.add(clearButton);

//southPanel.add(backButton);

frame.add(northPanel,BorderLayout.NORTH);

frame.add(centerPanel,BorderLayout.CENTER);

frame.add(southPanel,BorderLayout.SOUTH);

//设置输入字体

public void setFondAndColor(){

field.setForeground(Color.RED);

//设置字体从右起始

field.setHorizontalAlignment(JTextField.RIGHT);

public void showMi(){

frame.pack();

frame.setResizable(false);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public void addEventHander(){

allButtons[i].addActionListener(this);

clearButton.addActionListener(this);

// backButton.addActionListener(this);

String str = e.getActionCommand();//取得当前事件返回的值

if(x == 0){ //当x为0时表示还没有进行输入

result=str;

sb.append(str);

field.setText(str);

x = 1;

else if(x == 1){

result = result +str;

field.setText(result);

sb.delete(0,sb.length());

result = result+str;

result = str;

arrayList.clear();

result ="";

else{

else if("+*-/".indexOf(str)!=-1){

if(x == 0){

field.setText("");

result = result + str;

arrayList.add(sb.toString());

arrayList.add(str);

field.setText(result+str);

arrayList.add(result);

else if("=".equals(str)){

field.setText("0");

result = "0";

try{

arrayList = getResult(arrayList);

result = arrayList.get(0);

}catch(Exception e1){

field.setText("数据格式异常");

x = 0;

field.setText("数据格式错误.....");

else {

else if("CLEAR".equals(str)){

arrayList.add("0");

if(result.length()1){

result = result.substring(0,result.length()-1);

if(sb.length()0){

sb.delete(sb.length()-1,sb.length());

sb.delete(0,1);

result = "";

public static ArrayListString getResult(ArrayListString list){

String res = null;

String[] s = {"/","*","-","+"};

int i=0;

if(list.size()1){

for(;is.length;){

if(s[i].equals("/")){

for(int j=0;jlist.size();j++){

if(list.get(j).equals(s[i])){

res = Double.toString(Double.parseDouble(list.get(j-1))/Double.parseDouble(list.get(j+1)));

//本地的数据格式

NumberFormat nf = NumberFormat.getInstance();

res = nf.format(Double.parseDouble(res));

res = getChange(res);

list.set(j-1,res);

list.remove(j);

getResult(list);

i++;

else if(s[i].equals("*")){

res = Double.toString(Double.parseDouble(list.get(j-1))*Double.parseDouble(list.get(j+1)));

else if(s[i].equals("-")){

res = Double.toString(Double.parseDouble(list.get(j-1))-Double.parseDouble(list.get(j+1)));

NumberFormat nf = NumberFormat.getNumberInstance();

res = Double.toString(Double.parseDouble(list.get(j-1))+Double.parseDouble(list.get(j+1)));

return list;

//对数字字符串进行排除不必要符号

public static String getChange(String res){

String s_temp = "";

char[] c = new char[res.length()];

for(int k=0;kc.length;k++){

c[k] = res.charAt(k);

s_temp += c[k];

return s_temp;

public static void main(String[] args){

new CalculatorA().showMi();

java编程,用代码实现计算器类(Calculator)

public class Calculator {

private int number1;

this.number1 = number1;

public double add() {

public double subtract() {

public double multiple() {

return 0;

public class TestCalculator {

System.out.println(calculator.add());

System.out.println(calculator.subtract());

System.out.println(calculator.multiple());

java编一个计算器的代码

界面漂亮堪比系统自带计算器,功能完美加减乘除开平方等等全部具备,还有清零按钮,小数点的使用,连加连乘功能完全参考系统官方计算器经过长期调试改进而成,马上拷贝代码拿去试试看吧,绝不后悔!

代码如下:

import java.awt.event.*;

import java.util.*;

public class Counter {

CounterFrame frame = new CounterFrame();

frame.show();

class CounterFrame extends JFrame {

public CounterFrame() {

JMenuBar menuBar = new JMenuBar();

JMenu menuFile = new JMenu();

JMenu menuFile1 = new JMenu();

JMenuItem menuFileExit = new JMenuItem();

menuFile.setText("文件");

menuFileExit.setText("退出");

menuFileExit.addActionListener

(

new ActionListener() {

CounterFrame.this.windowClosed();

);

menuFile.add(menuFileExit);

menuBar.add(menuFile);

menuBar.add(menuFile1);

setTitle("计算器");

setJMenuBar(menuBar);

this.getContentPane().add(new Allpanel());

this.addWindowListener

new WindowAdapter() {

public void windowClosing(WindowEvent e) {

protected void windowClosed() {

System.exit(0);

class Tool {

public static Tool instance;

private Tool() {

this.field.setHorizontalAlignment(JTextField.RIGHT);

public static Tool getinstance()

if(instance==null)

instance=new Tool();

return instance;

public JTextField getfield()

return (this.field);

class Allpanel extends JPanel {

public Allpanel() {

Northpanel np=new Northpanel();

Centerpanel cp=new Centerpanel();

this.add(np,BorderLayout.NORTH);

this.add(cp,BorderLayout.CENTER);

class Centercenter extends JPanel {

static Vector Vec=new Vector();

static Vector vc=new Vector();

static Vector vc1=new Vector();

static String begin="yes";

static double add;

static double jq;

static double cs;

static double cq;

static double dy;

static String jg;

static String what;

static double tool=0;

static String to="yes";

/**

* Method Centercenter

public Centercenter() {

// TODO: Add your code here

final JTextField text=Tool.getinstance().getfield();

final JButton b=new JButton(arg[i]);

//this.add(new JButton(arg[i]));

this.add(b);

b.addActionListener(new ActionListener()

public void actionPerformed(ActionEvent e)

String mark=b.getText();

String ma=text.getText();

text.setText("0."+mark);

else if(vc.contains("a"))

vc.clear();

text.setText(mark);

Vec.clear();

Vec.add(mark);

text.setText(ma.trim()+mark);

begin="no";

to="yes";

});

String mar=b.getText();

String m=text.getText();

if("yes".equals(begin))

if(vc1.contains("v1"))

vc1.clear();

if(!Vec.contains(".")!vc.contains("a"))

text.setText(m.trim()+mar);

Vec.add(".");

add=Double.parseDouble(ma);

if(what==null)

tool=add;

what="add";

tool=tool+add;

text.setText(String.valueOf((tool)));

vc.add("a");

vc1.add("v1");

to="+";

jq=Double.parseDouble(ma);

tool=jq;

what="jq";

tool=tool-jq;

to="-";

cq=Double.parseDouble(ma);

tool=cq;

what="cq";

tool=tool/cq;

to="/";

text.setText(String.valueOf(Math.sqrt(cq)));

cs=Double.parseDouble(ma);

tool=cs;

what="cs";

tool=tool*cs;

to="*";

dy=Double.parseDouble(ma);

if(what=="add")

jg=String.valueOf((tool+dy));

if(what=="jq")

jg=String.valueOf((tool-dy));

if(what=="cs")

jg=String.valueOf((tool*dy));

if(what=="cq")

jg=String.valueOf((tool/dy));

if(to=="+")

jg=String.valueOf(tool+dy);

else if(to=="-")

jg=String.valueOf(dy-tool);

else if(to=="*")

jg=String.valueOf(dy*tool);

else if(to=="/")

jg=String.valueOf(dy/tool);

jg=String.valueOf(dy);

text.setText(jg);

what=null;

tool=0;

class Centernorth extends JPanel {

public Centernorth() {

JButton jb1=new JButton("Backspace");

this.add(jb1);

jb1.addActionListener(new ActionListener(){

String back=Tool.getinstance().getfield().getText();

text.setText(backmethod(back));

Centercenter.Vec.remove(Centercenter.Vec.size()-1);

text.setText("0.");

Centercenter.Vec.clear();

Centercenter.Vec.add(".");

Centercenter.vc.add("a");

Centercenter.begin="yes";

Centercenter.vc1.clear();

Centercenter.what=null;

Centercenter.tool=0;

public String backmethod(String str)

return str.substring(0,str.length()-1);

class Centerpanel extends JPanel {

public Centerpanel() {

Centernorth cn=new Centernorth();

Centercenter cc=new Centercenter();

Centerwest cw=new Centerwest();

this.add(cn,BorderLayout.NORTH);

this.add(cc,BorderLayout.CENTER);

this.add(cw,BorderLayout.WEST);

class Centerwest extends JPanel {

public Centerwest() {

this.add(new JButton("MC"));

this.add(new JButton("MR"));

this.add(new JButton("MS"));

this.add(new JButton("M+"));

class Northpanel extends JPanel {

private JTextField tf;

public Northpanel() {

tf=Tool.getinstance().getfield();

this.add(tf);

---------------------------------------------------------------------------

=============<<按你要求特意后改过的最简单功能的代码如下>>========================

static Vector Vec=new Vector();

static Vector vc=new Vector();

static Vector vc1=new Vector();

static String begin="yes";

static double add;

static double jq;

static double cs;

static double cq;

static double dy;

static String jg;

static String what;

static double tool=0;

static String to="yes";

if(i==11)

------------------------------------------------------------

才子_辉祝您愉快!

以上就是土嘎嘎小编为大家整理的计算器编程代码java相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!

版权声明:倡导尊重与保护知识产权。未经许可,任何人不得复制、转载、或以其他方式使用本站《原创》内容,违者将追究其法律责任。本站文章内容,部分图片来源于网络,如有侵权,请联系我们修改或者删除处理。

编辑推荐

热门文章