用Java设计一个简单的计算器。

头像
果果果大美   2021-09-18   2542浏览
已有36条回答
头像
0密星猛龙0
2023-05-10

说实在的,你写的这个计算器不怎么样。特别是布局。
我给你一个很简单的吧。你自己学习一下。。

import java.awt.*;
import java.awt.event.*;
/**
*
* @author zzj
*
*/
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;
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]);
} //创建按钮 并到P2
b[16].setBackground(Color.yellow);
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, "North");
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() == "=") {
jisuan();
str = String.valueOf(a);
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());
else if (s == "-")
a -= Double.parseDouble(txt.getText());
else if (s == "*")
a *= Double.parseDouble(txt.getText());
else if (s == "/")
a /= Double.parseDouble(txt.getText());
else
a = Double.parseDouble(txt.getText());
}
}
}

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

66

头像
弱智好儿童
2023-03-17

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.JOptionPane;

public class Calculator extends Applet implements ActionListener{
Button backButton=new Button("退格");
Button clearButton=new Button("清除");
Panel p1 = new Panel(new FlowLayout());
Panel p2 = new Panel(new GridLayout(2,1));
Panel p3 = new Panel(new GridLayout(4,5,5,5));
TextField t=new TextField("0");
float num1=0;
char ch='#';boolean can=false;
public void init(){
t.setFont(new Font("宋体",Font.BOLD,25));
backButton.setFont(new Font("黑体",Font.BOLD,15));
backButton.setForeground(Color.red);
clearButton.setFont(new Font("黑体",Font.BOLD,15));
clearButton.setForeground(Color.red);
p1.add(backButton);
p1.add(clearButton);
backButton.addActionListener(this);
clearButton.addActionListener(this);
p2.add(t);
p2.add(p1);
p2.setBackground(Color.black);
p3.setBackground(Color.black);
this.setLayout(new BorderLayout());
this.add(p2,"North");
this.add(p3,"Center");
String buttonStr = "789/A456*B123-C0.D+=";
for (int i = 0; i < buttonStr.length(); i++)
this.addButton(p3,buttonStr.substring(i, i + 1));
}
private void addButton(Container c, String s)
{Button b = new Button(s);
if (s.equals("A"))
b.setLabel("sqrt");
else if (s.equals("B"))
b.setLabel("1/x");
else if (s.equals("C"))
b.setLabel("%");
else if (s.equals("D"))
b.setLabel("+/-");
b.setForeground(Color.blue);
b.setFont(new Font("黑体",Font.BOLD,15));
c.add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
String act=e.getActionCommand();
if(e.getSource()==backButton){
if(t.getText().length()>1)t.setText(t.getText().substring(0, t.getText().length()-1));
else t.setText("0");
return;}
if(e.getSource()==clearButton){t.setText("0");ch='#';return;}
if(act.equals("+/-")){
if(t.getText().charAt(0)!='-')t.setText("-"+t.getText());
else t.setText(t.getText().substring(1));return;
}
if(act.equals(".")){t.setText(t.getText()+act);return;}
if(act!="1/x"&&act.charAt(0)>='0'&&act.charAt(0)<='9'){
if(can){t.setText(act);can=false;}
else{try{if(Float.parseFloat(t.getText())==0)
{if(t.getText().equals("0."))t.setText(t.getText()+act);
else t.setText(act);
return;
}
else {t.setText(t.getText()+act);return;}
}catch(NumberFormatException e1){
JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
}

if(act.equals("+")||act.equals("-")||act.equals("*")||act.equals("/")||act.equals("%")){
if(ch!='#'){try{num1=cacu(num1,ch,Float.parseFloat(t.getText()));
t.setText(String.valueOf(num1));ch=act.charAt(0);can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
else{try{num1=Float.parseFloat(t.getText());
ch=act.charAt(0);can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
}
if(act.equals("sqrt")){try{float num=(float)Math.sqrt(Float.parseFloat(t.getText()));
t.setText(String.valueOf(num));can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
if(act.equals("1/x")){try{float num=1/Float.parseFloat(t.getText());
t.setText(String.valueOf(num));can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
catch(ArithmeticException e1){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
if(act.equals("=")){can=true;
try{if(ch=='#')return;
float num=Float.parseFloat(t.getText());
num1=cacu(num1,ch,num);
t.setText(String.valueOf(num1));
ch='#';return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
}
public float cacu(float a,char c,float b){
float sum;
switch(c){
case '+':sum=a+b;break;
case '-':sum=a-b;break;
case '*':sum=a*b;break;
case '/':if(b==0){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return 0;}sum=a/b;break;
case '%':if(b==0){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return 0;}sum=a%b;break;
default:return 0;
}
return sum;
}
}

154

头像
Lemonice柠檬冰
2023-01-04

无聊写了个,修复了下Bug:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Calculate extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;

private JButton plus, reduce, multiply, divice, reset;
private JTextField one, two, result;
private boolean device_falg = false;

private final int width = 400, height = 300;

public Calculate() {
super("修改密");
this.setLayout(null);
this.setSize(width, height);
init();
Layout();
}

public void init() {
plus = new JButton("加 ");
reduce = new JButton("减 ");
multiply = new JButton("乘 ");
divice = new JButton("除 ");
reset = new JButton("清空");
one = new JTextField();
two = new JTextField();
result = new JTextField();
}

public void Layout() {
this.add(new JLabel("第一个数")).setBounds(20, 10, 60, 80);
this.add(one).setBounds(100, 38, 100, 25);
this.add(new JLabel("第二个数")).setBounds(20, 40, 60, 80);
this.add(two).setBounds(100, 70, 100, 25);
this.add(new JLabel("结果")).setBounds(20, 85, 60, 80);
this.add(result).setBounds(100, 110, 100, 25);

this.add(plus).setBounds(70, 170, 80, 25);
this.add(reduce).setBounds(200, 170, 80, 25);
this.add(multiply).setBounds(70, 200, 80, 25);
this.add(divice).setBounds(200, 200, 80, 25);

this.add(reset).setBounds(300, 220, 80, 25);

plus.addActionListener(this);
reduce.addActionListener(this);
multiply.addActionListener(this);
divice.addActionListener(this);
reset.addActionListener(this);

this.setVisible(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}

public boolean Format() {
boolean FLAG = false;
boolean flag = false;
String one = this.one.getText().toString().trim();
String two = this.two.getText().toString().trim();

if (one == null || one.equals("") || two == null || two.equals("")) {
JOptionPane.showMessageDialog(getParent(), "请输入完整信息!");
FLAG = false;
flag = true;
}

boolean boll_1 = one.matches("[d]{1,100}");
boolean boll_2 = two.matches("[d]{1,100}");
boolean boll_3 = one.matches("[d]{1,100}+[.]+[d]{1,100}");
boolean boll_4 = two.matches("[d]{1,100}+[.]+[d]{1,100}");
if (flag) {
return false;
}
if ((boll_1 && boll_2) || (boll_3 && boll_4) || (boll_1 && boll_4)
|| (boll_3 && boll_2)) {
FLAG = true;
} else {
JOptionPane.showMessageDialog(getParent(), "请输入数字!");
FLAG = false;
}

if (FLAG && device_falg) {
if (Double.parseDouble(two) == 0) {
JOptionPane.showMessageDialog(getParent(), "被除数不能为0!");
FLAG = false;
device_falg=false;
}
}

return FLAG;
}

public double Plus(double one, double two) {
return one + two;
}

public double Multiply(double one, double two) {
return one * two;
}

public double Divice(double one, double two) {
return one / two;
}

public double Reduce(double one, double two) {
return one - two;
}

public void Clear() {
one.setText("");
two.setText("");
result.setText("");
}

@Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == reset) {
Clear();
return;
}
if (o == divice) {
device_falg = true;
}
if (!Format()) {
return;
}
double one = Double.parseDouble(this.one.getText());
double two = Double.parseDouble(this.two.getText());
double result = 0;
if (o == plus) {
result = Plus(one, two);
} else if (o == reduce) {
result = Reduce(one, two);
} else if (o == multiply) {
result = Multiply(one, two);
} else if (o == divice) {
result = Divice(one, two);
}
this.result.setText("" + result);
}
public static void main(String[] args) {
new Calculate();
}
}

163

头像
早秋2013
2022-09-09

比一楼的简单

package com.isoftstone.baidu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class CalcDemo extends JFrame {

private static final long serialVersionUID = 111111L;
private JLabel label1 = new JLabel();
private JLabel label2 = new JLabel();
private JLabel label3 = new JLabel();
private JTextField field1 = new JTextField();
private JTextField field2 = new JTextField();
private JTextField field3 = new JTextField();
private JButton button1 = new JButton();
private JButton button2 = new JButton();
private JButton button3 = new JButton();
private JButton button4 = new JButton();

public static void main(String[] args) {
new CalcDemo();
}

public CalcDemo() {
super("简易计算器");
try {
init();
} catch (Exception e) {
e.printStackTrace();
}
}

private void init() {
this.setSize(300, 300);
label1.setText("第一个数:");
label2.setText("第二个数:");
label3.setText("结果:");
button1.setText("加法");
button2.setText("减法");
button3.setText("乘法");
button4.setText("除法");
label1.setBounds(10, 10, 100, 22);
label2.setBounds(10, 35, 100, 22);
label3.setBounds(10, 60, 100, 22);
field1.setBounds(110, 10, 100, 22);
field2.setBounds(110, 35, 100, 22);
field3.setBounds(110, 60, 100, 22);
button1.setBounds(10, 85, 100, 22);
button2.setBounds(110, 85, 100, 22);
button3.setBounds(110, 110, 100, 22);
button4.setBounds(10, 110, 100, 22);
button1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
calculate(1);
}
});
button2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
calculate(2);
}
});
button3.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
calculate(3);
}
});
button4.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
calculate(4);
}
});
JPanel panel = (JPanel) this.getContentPane();
panel.setLayout(null);
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(field1);
panel.add(field2);
panel.add(field3);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);

}

private void calculate(int operators) {
try {
double num1 = Double.parseDouble(field1.getText());
double num2 = Double.parseDouble(field2.getText());
switch (operators) {
case 1:
field3.setText((num1 + num2) + "");
break;
case 2:
field3.setText((num1 - num2) + "");
break;
case 3:
field3.setText((num1 * num2) + "");
break;
case 4:
field3.setText((num1 / num2) + "");
break;
default:
break;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "请输入正确的数值!!!", "警告", 1);
}
}
}

92

头像
涅槃0531
2022-08-29

百度一下很多的,何况这代也不难,自己理一下很也能弄出来,给button, 中取两个文本框的值,将两个文本框的值转化为int(这时候可能会有异常,trycatch处理),在进行运算,最后将结果放入结果文本框中

128

相关问题

用Java设计一个简单的计算器。
天使之懿727 1970-01-01

设计一个简单的计算器,能够对两个数据进行“加、减、乘、除”运算。要求:合理应用布局设计,注重界面美观、友好,要求处理NumberFormatException异常。

用java设计计算器
fionazhang77 1970-01-01

用java编写一个简单的计算器(用于数字1、2、3、4的计算)
起舞徘徊风露下 1970-01-01

其中+、-、*、/都是button按钮右上角右缩小、最大化、关闭按钮。关闭按钮能用

Java设计计算器
chocolate宸 1970-01-01

高手帮忙用Java设计个计算器程序!
小琳子雄霸天下 1970-01-01

用Java实现一个applet计算器程序,要有+,-,*,/功能。会做的朋友帮帮忙,小弟先谢过各位了!还有更简单点的答案吗?

用Java设计一个图形界面(GUI)的计算器应用程序。
欧阳安Muse 1970-01-01

设计的计算器应用程序可以完成家法、减法、乘法、除法和取余运算。且有小数点、正负号、求倒数、退格和清零功能。急急急!!!拜托!!!!

java计算器课设
天道酬勤1212 1970-01-01

最新问答

排水论文在哪发?
伊兰0518 2021-09-19

小区市外排水论文发哪个杂志可以呢?我需要发表一篇这方面的论文。

word转pdf,为什么不显示图片图片?
花花的老妈 2021-09-19

我想把论文从word格式转换成PDF格式,用的金山WPS,可转换完成之后,里面的流程图就不见了,空白~~这是为什么呢?谁能帮我解决一下!谢谢!

公众号与小程序有什么区别
汤糖躺烫湯 2021-09-19

公众号与小程序有什么区别

如何制作电子小报
dream959595 2021-09-19

镀铬什么意思
autumngold 2021-09-19

镀铬什么意思

中国电影艺术的思想
幸福顺延 2021-09-19

中国针灸大纲作者是谁?
王子麻麻 2021-09-19

热门问答

排水论文在哪发?
伊兰0518 2021-09-19

小区市外排水论文发哪个杂志可以呢?我需要发表一篇这方面的论文。

word转pdf,为什么不显示图片图片?
花花的老妈 2021-09-19

我想把论文从word格式转换成PDF格式,用的金山WPS,可转换完成之后,里面的流程图就不见了,空白~~这是为什么呢?谁能帮我解决一下!谢谢!

公众号与小程序有什么区别
汤糖躺烫湯 2021-09-19

公众号与小程序有什么区别

如何制作电子小报
dream959595 2021-09-19

镀铬什么意思
autumngold 2021-09-19

镀铬什么意思

中国电影艺术的思想
幸福顺延 2021-09-19

中国针灸大纲作者是谁?
王子麻麻 2021-09-19

Coptyright © www.lw85.com电脑版