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

2024-12-02 16:35:07
推荐回答(5个)
回答1:

学java的时候自己编的,很简单,能够连续输入计算式后进行计算
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**简易计算器,能够进行简单的计算
*
* @see 2008.12.9
*/
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; //用来判断上一次的事件类型
String str = "123+456-789*0.=/";
ArrayList arrayList = new ArrayList();//保存计算式,通过方法进行运算

public CalculatorA(){

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

field = new JTextField(25);

allButtons = new JButton[16];
for(int i=0;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());
centerPanel.setLayout(new GridLayout(4,4));
southPanel.setLayout(new FlowLayout());

northPanel.add(field);
for(int i=0;i 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.setFont(new Font("宋体",Font.BOLD,24));
field.setBackground(new Color(100,200,200));
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(){
for(int i=0;i allButtons[i].addActionListener(this);
}
clearButton.addActionListener(this);
// backButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();//取得当前事件返回的值
if("0123456789.".indexOf(str)!=-1){
if(x == 0){ //当x为0时表示还没有进行输入
result=str;
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 1){
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 2){
sb.delete(0,sb.length());
result = result+str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 3){
result = str;
sb.delete(0,sb.length());
arrayList.clear();
field.setText(str);
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
result = str;
sb.append(str);
field.setText(str);
x = 1;
}
else{
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
}
else if("+*-/".indexOf(str)!=-1){
if(x == 0){
field.setText("");
x = 2;
}
else if(x == 1){
result = result + str;
arrayList.add(sb.toString());
arrayList.add(str);
sb.append(str);
field.setText(result);
x = 2;
}
else if(x == 2){
x = 2;
}
else if(x == 3){
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 2;
}
else{
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
}
else if("=".equals(str)){
if(x == 0){
field.setText("0");
arrayList.clear();
result = "0";
x = 3;
}
else if(x == 1){
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("数据格式异常");
x = 0;
}
}
else if(x == 2){
field.setText("数据格式错误.....");
arrayList.clear();
x = 0;
}
else if(x == 3){
field.setText(result);
x = 3;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 3;
}
else {
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("数据格式异常");
x = 0;
}
}
}
else if("CLEAR".equals(str)){
arrayList.clear();
field.setText("0");
arrayList.add("0");
x = 4;
}
else{
if(result.length()>1){
result = result.substring(0,result.length()-1);
if(sb.length()>0){
sb.delete(sb.length()-1,sb.length());
}
else {
sb.delete(0,1);
}
field.setText(result);
x = 5;
}
else{
result = "";
sb.delete(0,sb.length());
arrayList.clear();
field.setText("0");
x = 0;
}
}
}
public static ArrayList getResult(ArrayList list){
String res = null;
String[] s = {"/","*","-","+"};
int i=0;
if(list.size()>1){
for(;i if(s[i].equals("/")){
for(int j=0;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);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("*")){
for(int j=0;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);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("-")){
for(int j=0;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.getNumberInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else {
for(int j=0;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);
list.remove(j);
getResult(list);
}
}
i++;
}
}
}
return list;
}
//对数字字符串进行排除不必要符号
public static String getChange(String res){
String s_temp = "";
char[] c = new char[res.length()];
for(int k=0;k c[k] = res.charAt(k);
}
for(int k=0;k if((c[k]>= '0' && c[k]<= '9')|| c[k] == '.'){
s_temp += c[k];
}
}
return s_temp;
}
public static void main(String[] args){
new CalculatorA().showMi();
}
}

回答2:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
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;

public class CalculatorB implements ActionListener {
private JFrame frame;

private JTextField field;

private JButton[] allButtons;

private JButton clearButton;

// 构造初始化 成员变量
public CalculatorB() {
frame = new JFrame("Calculator v1.1");
field = new JTextField(25);
allButtons = new JButton[16];
String str = "123+456-789*0.=/";
for (int i = 0; i < 16; i++) {
allButtons[i] = new JButton(str.substring(i, i + 1));
}
clearButton = new JButton("CLEAR");
// 调用界面的初始化方法
init();
// 调用设置文本框的字体和颜色 方法
setFontAndColor();
addEventHandler();
}

public void addEventHandler() {
for (int i = 0; i < allButtons.length; i++) {
allButtons[i].addActionListener(this);
clearButton.addActionListener(this);
}
}

private String op = null;

private String m = null;

private String n = null;

private boolean cls = false;

private void setResult() {
if (field.getText().equals("")) {
cls = true;
m = null;
n = null;
} else if (m != null) {
n = field.getText();
if (op.equals("+")) {
field.setText(Double.parseDouble(m) + Double.parseDouble(n)
+ "");
} else if (op.equals("-")) {
field.setText(Double.parseDouble(m) - Double.parseDouble(n)
+ "");
} else if (op.equals("*")) {
field.setText(Double.parseDouble(m) * Double.parseDouble(n)
+ "");
} else if (op.equals("/")) {
field.setText(Double.parseDouble(m) / Double.parseDouble(n)
+ "");
}
cls = true;
m = null;
n = null;
}

}

public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();// 得到被点的按钮名称
if ("0123456789.".indexOf(str) != -1) {
if (cls) {
field.setText("");
cls = false;
}
field.setText(field.getText() + str);
} else if ("+-*/".indexOf(str) != -1) {
if (field.getText().equals("")) {
op = str;
} else if (m == null) {
m = field.getText();
op = str;
field.setText("");
} else if (m != null) {
setResult();
m = field.getText();
op = str;
}

} else if (str.equals("=")) {
setResult();
} else if (str.equals("CLEAR")) {
field.setText("");
m = null;
n = null;
}
}

public void init() {
frame.setLayout(new BorderLayout());
JPanel northPannel = new JPanel();
JPanel centerPannel = new JPanel();
JPanel southPannel = new JPanel();
northPannel.setLayout(new FlowLayout());
centerPannel.setLayout(new GridLayout(4, 4));
southPannel.setLayout(new FlowLayout());
northPannel.add(field);
southPannel.add(clearButton);
for (int i = 0; i < allButtons.length; i++) {
centerPannel.add(allButtons[i]);
}
frame.add(northPannel, BorderLayout.NORTH);
frame.add(southPannel, BorderLayout.SOUTH);
frame.add(centerPannel, BorderLayout.CENTER);

}

public void setFontAndColor() {
field.setFont(new Font("宋体", Font.BOLD, 20));
field.setForeground(Color.PINK);
field.setBackground(new Color(0x2a, 0x3b, 0x4f));
}

public void showMe() {
frame.pack(); // 系统调整大小---很重要
// frame.setSize(600, 400);// 自定义窗体大小
frame.setLocation(500, 400);// 设置窗体的启动位置
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
}

public static void main(String[] args) {
new CalculatorB().showMe();
}

}

以上代码是我的原创回答,可以直接运行的代码。并且此计算器可以实现连续计算,楼主试试去,有什么意见和建议再提

回答3:

看看这个吧我觉得很简单啊声明不是我写的,我写的比这个麻烦呵呵
import java.awt.*;
import java.awt.event.*;

public class Jisuanqi extends WindowAdapter {
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
TextField txt;
private Button[] b = new Button[17];

private String ss[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
"3", "*", "清空", "0", "=", "/", "关闭" };

static double a;

int num;

static String s, str;// 定义变量 创建对像

public static void main(String args[]) {
(new Jisuanqi()).frame();
}

public void frame() {
Frame fm = new Frame("简单计算器");
for (int i = 0; i <= 16; i++) {
b[i] = new Button(ss[i]);
}
for (int i = 0; i <= 15; i++) {
p2.add(b[i]);
}

fm.setBounds(300, 200, 200, 200);
// 创建按钮 并添加到P2
txt = new TextField(15);
txt.setEditable(false);
for (int i = 0; i <= 16; i++) {
b[i].addActionListener(new buttonlistener());// 添加监听器
}
b[16].addActionListener(new close());
fm.addWindowListener(this);
// fm.setBackground(Color.red);
p1.setLayout(new BorderLayout());
p1.add(txt, "Center");
p2.setLayout(new GridLayout(4, 4));
p3.setLayout(new BorderLayout());
p3.add(b[16]);
fm.add(p1, "North");
fm.add(p2, "Center");
fm.add(p3, "South");
fm.pack();
fm.setVisible(true);// 都是些窗中设置 添加相关组件和监听器
}

public void windowClosing(WindowEvent e) {
System.exit(0);// 退出系统
}

class buttonlistener implements ActionListener {// 编写监听器事件 通过按键得出给果
public void actionPerformed(ActionEvent e) {
Button btn = (Button) e.getSource();
if (btn.getLabel() == "=") {
if (!txt.getText().equals(""))
jisuan();
str = String.valueOf(num);
txt.setText(str);
s = "";
} else if (btn.getLabel() == "+") {
jisuan();
txt.setText("");
s = "+";
} else if (btn.getLabel() == "-") {
jisuan();
txt.setText("");
s = "-";
} else if (btn.getLabel() == "/") {
jisuan();
txt.setText("");
s = "/";

} else if (btn.getLabel() == "*") {
jisuan();
txt.setText("");
s = "*";
} else {
txt.setText(txt.getText() + btn.getLabel());

if (btn.getLabel() == "清空")
txt.setText("");
}
}

public void jisuan() {// 编写具体计算方法

if (s == "+") {
a += Double.parseDouble(txt.getText());
num = (int) a;
} else if (s == "-")
{a -= Double.parseDouble(txt.getText());
num = (int) a;}
else if (s == "*")
{a *= Double.parseDouble(txt.getText());
num = (int) a;
}
else if (s == "/"){
a /= Double.parseDouble(txt.getText());
num = (int) a;}
else
a = Double.parseDouble(txt.getText());
num = (int) a;
}
}
}

class close implements ActionListener {// 退出
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}

回答4:

import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
class Suan extends Frame implements ActionListener
{
Label label1,label2,label3,label4;
TextField field1,field2,field3;
Button button1,button2,button3,button4,button5;
Suan(String s)
{
super(s);
label1=new Label("第一个数");
label2=new Label("第二个数");
label3=new Label("结果");
label4=new Label(" ");
field1=new TextField(15);
field2=new TextField(15);
field3=new TextField(15);
button1=new Button("加 +");
button2=new Button("减 -");
button3=new Button("乘 *");
button4=new Button("除 /");
button5=new Button("清除");
add(label1);
add(field1);
add(label2);
add(field2);
add(label3);
add(field3);
add(button1);button1.addActionListener(this);
add(button2);button2.addActionListener(this);
add(button3);button3.addActionListener(this);
add(button4);button4.addActionListener(this);
add(button5);button5.addActionListener(this);
add(label4);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent m)
{
System.exit(0);
}
});
setLayout(new FlowLayout());
setBounds(300,300,800,200);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{
String s1=null,s2=null;
try {
s1=field1.getText();
s2=field2.getText();
}
catch (Exception ex)
{
label4.setBackground(Color.RED);
label4.setText("输入的格式错误");
}
try {
if(e.getSource()==button1)
{
double a1=Double.parseDouble(s1);
double a2=Double.parseDouble(s2);
double a3=a1+a2;
String s3=String.valueOf(a3);
field3.setText(s3);
}
if(e.getSource()==button2)
{
double a1=Double.parseDouble(s1);
double a2=Double.parseDouble(s2);
double a3=a1-a2;
String s3=String.valueOf(a3);
field3.setText(s3);
}
if(e.getSource()==button3)
{
double a1=Double.parseDouble(s1);
double a2=Double.parseDouble(s2);
double a3=a1*a2;
String s3=String.valueOf(a3);
field3.setText(s3);
}
if(e.getSource()==button4)
{
double a1=Double.parseDouble(s1);
double a2=Double.parseDouble(s2);
double a3=a1/a2;
String s3=String.valueOf(a3);
field3.setText(s3);
}
if(e.getSource()==button5)
{
field1.setText(null);
field2.setText(null);
field3.setText(null);
label4.setBackground(Color.white);
label4.setText(null);
}
}
catch (Exception ex)
{
label4.setBackground(Color.RED);
label4.setText("输入的格式错误");
JOptionPane.showMessageDialog(this,"你输入了非法字符","警告对话框",JOptionPane.WARNING_MESSAGE);

}

}
}
public class jisuanqi
{
public static void main(String s[])
{
new Suan("我的计算器");
}
}

回答5:

import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
class Suan extends Frame implements ActionListener
{
Label label1,label2,label3,label4;
TextField field1,field2,field3;
Button button1,button2,button3,button4,button5;
Suan(String s)
{
super(s);
label1=new Label("第一个数");
label2=new Label("第二个数");
label3=new Label("结果");
label4=new Label(" ");
field1=new TextField(15);
field2=new TextField(15);
field3=new TextField(15);
button1=new Button("加 +");
button2=new Button("减 -");
button3=new Button("乘 *");
button4=new Button("除 /");
button5=new Button("清除");
add(label1);
add(field1);
add(label2);
add(field2);
add(label3);
add(field3);
add(button1);button1.addActionListener(this);
add(button2);button2.addActionListener(this);
add(button3);button3.addActionListener(this);
add(button4);button4.addActionListener(this);
add(button5);button5.addActionListener(this);
add(label4);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent m)
{
System.exit(0);
}
});
setLayout(new FlowLayout());
setBounds(300,300,800,200);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{
String s1=null,s2=null;
try {
s1=field1.getText();
s2=field2.getText();
}
catch (Exception ex)
{
label4.setBackground(Color.RED);
label4.setText("输入的格式错误");
}
try {
if(e.getSource()==button1)
{
double a1=Double.parseDouble(s1);
double a2=Double.parseDouble(s2);
double a3=a1+a2;
String s3=String.valueOf(a3);
field3.setText(s3);
}
if(e.getSource()==button2)
{
double a1=Double.parseDouble(s1);
double a2=Double.parseDouble(s2);
double a3=a1-a2;
String s3=String.valueOf(a3);
field3.setText(s3);
}
if(e.getSource()==button3)
{
double a1=Double.parseDouble(s1);
double a2=Double.parseDouble(s2);
double a3=a1*a2;
String s3=String.valueOf(a3);
field3.setText(s3);
}
if(e.getSource()==button4)
{
double a1=Double.parseDouble(s1);
double a2=Double.parseDouble(s2);
double a3=a1/a2;
String s3=String.valueOf(a3);
field3.setText(s3);
}
if(e.getSource()==button5)
{
field1.setText(null);
field2.setText(null);
field3.setText(null);
label4.setBackground(Color.white);
label4.setText(null);
}
}
catch (Exception ex)
{
label4.setBackground(Color.RED);
label4.setText("输入的格式错误");
JOptionPane.showMessageDialog(this,"你输入了非法字符","警告对话框",JOptionPane.WARNING_MESSAGE);

}

}
}
public class jisuanqi
{
public static void main(String s[])
{
new Suan("我的计算器");
}
}

这些代码都好长哦,建议封装一下,要养成良好的习惯,不要习惯了写上帝类,那你一辈子就完了