当前位置:首页 » 编程语言 » 简单的java计算器

简单的java计算器

发布时间: 2022-06-04 08:42:48

1. java简单计算器

import java.util.Scanner;

public class Calculator {
@SuppressWarnings("resource")
public static void main(String[] args) {
System.out.println("+------------------+");
System.out.println("| JAVA计算器例子 |");
System.out.println("+------------------+");
System.out.println("规则:操作数必须为整数,若除法运算则除数不能为零,");
System.out.println("运算符必须为'+,-,*,%'中的一种");
while (true) {
System.out.println("+-------------------------------------------+");
System.out.println("| + 选 1,- 选 2,* 选 3,/ 选 4,退出 选 0 |");
System.out.println("+-------------------------------------------+");
System.out.println("请输入您的选择:");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if ("0".equals(input)) {
System.exit(0);
break;
} else {
calculation(input);
}
}
}
@SuppressWarnings("resource")
private static void calculation(String param) {
System.out.println("请输入第一个数字:");
Scanner scanner1 = new Scanner(System.in);
int num1 = scanner1.nextInt();
System.out.println("请输入第二个数字(如果是除法,不能输入0):");
Scanner scanner2 = new Scanner(System.in);
int num2 = scanner2.nextInt();
switch (param) {
case "1" :
System.out.println("本次的计算结果为:" + (num1 + num2));
break;
case "2" :
System.out.println("本次的计算结果为:" + (num1 - num2));
break;
case "3" :
System.out.println("本次的计算结果为:" + (num1 * num2));
break;
case "4" :
if (num2 == 0) {
System.out.println("除数为零,计算失败!!!");
} else {
System.out.println("本次的计算结果为:" + (num1 / num2));
}
break;
default :
System.out.println("输入有误,请重新输入。");
break;
}
}
}
上面是我写的代码,麻烦您看一下是否能满足要求。
下面是执行的结果:
+------------------+
| JAVA计算器例子 |
+------------------+
规则:操作数必须为整数,若除法运算则除数不能为零,
运算符必须为'+,-,*,%'中的一种
+-------------------------------------------+
| + 选 1,- 选 2,* 选 3,/ 选 4,退出 选 0 |
+-------------------------------------------+
请输入您的选择:
1
请输入第一个数字:
3
请输入第二个数字(如果是除法,不能输入0):
4
本次的计算结果为:7
+-------------------------------------------+
| + 选 1,- 选 2,* 选 3,/ 选 4,退出 选 0 |
+-------------------------------------------+
请输入您的选择:
5
请输入第一个数字:
0
请输入第二个数字(如果是除法,不能输入0):
6
输入有误,请重新输入。
+-------------------------------------------+
| + 选 1,- 选 2,* 选 3,/ 选 4,退出 选 0 |
+-------------------------------------------+
请输入您的选择:
4
请输入第一个数字:
6
请输入第二个数字(如果是除法,不能输入0):
3
本次的计算结果为:2
+-------------------------------------------+
| + 选 1,- 选 2,* 选 3,/ 选 4,退出 选 0 |
+-------------------------------------------+
请输入您的选择:
2
请输入第一个数字:
7
请输入第二个数字(如果是除法,不能输入0):
2
本次的计算结果为:5
+-------------------------------------------+
| + 选 1,- 选 2,* 选 3,/ 选 4,退出 选 0 |
+-------------------------------------------+
请输入您的选择:
3
请输入第一个数字:
7
请输入第二个数字(如果是除法,不能输入0):
8
本次的计算结果为:56
+-------------------------------------------+
| + 选 1,- 选 2,* 选 3,/ 选 4,退出 选 0 |
+-------------------------------------------+
请输入您的选择:
0

2. 用JAVA编写一个简单的计算器,要求如下

太麻烦了 说个思路, 过去字符串后 先获取+-*%的下标.然后然后分割,获取到一个数组或list
然后循环获取() 按照数学运算顺序拼起来,
然后把公式拆分一步一步操作就得出结果啦

3. 用java实现一个简单的计算器。

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

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);
}
}

4. 你好,怎样简单的用JAVA制作计算器

网上有很多代码啊,你可以很容易就搜到的。

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

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

importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JOptionPane;
importjavax.swing.JTextField;

{

=1L;

privateJButtonplus,rece,multiply,divice,reset;
privateJTextFieldone,two,result;
privatebooleandevice_falg=false;

privatefinalintwidth=400,height=300;

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

publicvoidinit(){
plus=newJButton("加");
rece=newJButton("减");
multiply=newJButton("乘");
divice=newJButton("除");
reset=newJButton("清空");
one=newJTextField();
two=newJTextField();
result=newJTextField();
}

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

this.add(plus).setBounds(70,170,80,25);
this.add(rece).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);
rece.addActionListener(this);
multiply.addActionListener(this);
divice.addActionListener(this);
reset.addActionListener(this);

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

publicbooleanFormat(){
booleanFLAG=false;
booleanflag=false;
Stringone=this.one.getText().toString().trim();
Stringtwo=this.two.getText().toString().trim();

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

booleanboll_1=one.matches("[\d]{1,100}");
booleanboll_2=two.matches("[\d]{1,100}");
booleanboll_3=one.matches("[\d]{1,100}+[.]+[\d]{1,100}");
booleanboll_4=two.matches("[\d]{1,100}+[.]+[\d]{1,100}");
if(flag){
returnfalse;
}
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;
}
}

returnFLAG;
}

publicdoublePlus(doubleone,doubletwo){
returnone+two;
}

publicdoubleMultiply(doubleone,doubletwo){
returnone*two;
}

publicdoubleDivice(doubleone,doubletwo){
returnone/two;
}

publicdoubleRece(doubleone,doubletwo){
returnone-two;
}

publicvoidClear(){
one.setText("");
two.setText("");
result.setText("");
}

@Override
publicvoidactionPerformed(ActionEvente){
Objecto=e.getSource();
if(o==reset){
Clear();
return;
}
if(o==divice){
device_falg=true;
}
if(!Format()){
return;
}
doubleone=Double.parseDouble(this.one.getText());
doubletwo=Double.parseDouble(this.two.getText());
doubleresult=0;
if(o==plus){
result=Plus(one,two);
}elseif(o==rece){
result=Rece(one,two);
}elseif(o==multiply){
result=Multiply(one,two);
}elseif(o==divice){
result=Divice(one,two);
}
this.result.setText(""+result);
}
publicstaticvoidmain(String[]args){
newCalculate();
}
}

6. 用java编写一个简单计算器

/*

* @(#)JCalculator.java 1.00 06/17/2015

*/

importjava.awt.*;

importjava.awt.event.*;

importjavax.swing.*;

/**

* A simple calculator program.

*<p>I saw this program in a QQ group, and help a friend correct it.</p>

*

*@authorSingyuenYip

*@version1.00 12/29/2009

*@seeJFrame

*@seeActionListener

*/

{

/**

* Serial Version UID

*/

= -169068472193786457L;

/**

* This class help close the Window.

*@authorSingyuenYip

*

*/

{

publicvoidwindowClosing(WindowEvent we) {

System.exit(0);

}

}

inti;

// Strings for Digit & Operator buttons.

privatefinalString[]str= {"7","8","9","/","4","5","6","*","1",

"2","3","-",".","0","=","+"};

// Build buttons.

JButton[]buttons=newJButton[str.length];

// For cancel or reset.

JButtonreset=newJButton("CE");

// Build the text field to show the result.

JTextFielddisplay=newJTextField("0");

/**

* Constructor without parameters.

*/

publicJCalculator() {

super("Calculator");

// Add a panel.

JPanel panel1 =newJPanel(newGridLayout(4, 4));

// panel1.setLayout(new GridLayout(4,4));

for(i= 0;i<str.length;i++) {

buttons[i] =newJButton(str[i]);

panel1.add(buttons[i]);

}

JPanel panel2 =newJPanel(newBorderLayout());

// panel2.setLayout(new BorderLayout());

panel2.add("Center",display);

panel2.add("East",reset);

// JPanel panel3 = new Panel();

getContentPane().setLayout(newBorderLayout());

getContentPane().add("North", panel2);

getContentPane().add("Center", panel1);

// Add action listener for each digit & operator button.

for(i= 0;i<str.length;i++)

buttons[i].addActionListener(this);

// Add listener for "reset" button.

reset.addActionListener(this);

// Add listener for "display" button.

display.addActionListener(this);

// The "close" button "X".

addWindowListener(newWindowCloser());

// Initialize the window size.

setSize(800, 800);

// Show the window.

// show(); Using show() while JDK version is below 1.5.

setVisible(true);

// Fit the certain size.

pack();

}

publicvoidactionPerformed(ActionEvent e) {

Object target = e.getSource();

String label = e.getActionCommand();

if(target ==reset)

handleReset();

elseif("0123456789.".indexOf(label) > 0)

handleNumber(label);

else

handleOperator(label);

}

// Is the first digit pressed?

booleanisFirstDigit=true;

/**

* Number handling.

*@paramkey the key of the button.

*/

publicvoidhandleNumber(String key) {

if(isFirstDigit)

display.setText(key);

elseif((key.equals(".")) && (display.getText().indexOf(".") < 0))

display.setText(display.getText() +".");

elseif(!key.equals("."))

display.setText(display.getText() + key);

isFirstDigit=false;

}

/**

* Reset the calculator.

*/

publicvoidhandleReset() {

display.setText("0");

isFirstDigit=true;

operator="=";

}

doublenumber= 0.0;

Stringoperator="=";

/**

* Handling the operation.

*@paramkey pressed operator's key.

*/

publicvoidhandleOperator(String key) {

if(operator.equals("+"))

number+= Double.valueOf(display.getText());

elseif(operator.equals("-"))

number-= Double.valueOf(display.getText());

elseif(operator.equals("*"))

number*= Double.valueOf(display.getText());

elseif(operator.equals("/"))

number/= Double.valueOf(display.getText());

elseif(operator.equals("="))

number= Double.valueOf(display.getText());

display.setText(String.valueOf(number));

operator= key;

isFirstDigit=true;

}

publicstaticvoidmain(String[] args) {

newJCalculator();

}

}


运行界面:

7. 用Java做一个简单的计算器

  1. 窗体
    package Calc;

    import java.awt.*;
    import java.awt.event.*;

    import javax.swing.*;

    /**
    *
    * 计算器程序
    *
    */
    public class CalcFrame extends JFrame {
    JButton[] buttons = new JButton[16];// 16个按钮

    StringBuffer sb = null;//

    JTextField text1 = null;// 计算器结果显示框

    String no1 = null;

    String sign = null;// 表示+-*/符号

    String[] s = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-",
    "*", "/", "=", "C" };// 面板上的字符

    public CalcFrame() {
    setTitle("计算器");
    setResizable(false);
    setBounds(200, 200, 300, 350);
    setLayout(null);

    sb = new StringBuffer();
    text1 = new JTextField();
    text1.setBounds(10, 10, 250, 30);// 设置位置
    text1.setFont(new Font("Arial", Font.PLAIN, 20));// 设置字体
    text1.setForeground(Color.RED);// 设置颜色
    add(text1);
    for (int i = 0; i < s.length; i++) {

    buttons[i] = new JButton(s[i]);
    buttons[i].setFont(new Font("Serif", Font.BOLD, 18));
    add(buttons[i]);
    }// 生成面板上的按钮.

    buttons[0].setBounds(10, 50, 50, 40);
    buttons[0].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(0);
    text1.setText(sb.toString());
    }

    });
    buttons[1].setBounds(70, 50, 50, 40);
    buttons[1].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(1);
    text1.setText(sb.toString());
    }

    });
    buttons[2].setBounds(130, 50, 50, 40);
    buttons[2].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(2);
    text1.setText(sb.toString());
    }

    });
    buttons[3].setBounds(190, 50, 50, 40);
    buttons[3].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(3);
    text1.setText(sb.toString());
    }

    });
    buttons[4].setBounds(10, 100, 50, 40);
    buttons[4].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(4);
    text1.setText(sb.toString());
    }

    });
    buttons[5].setBounds(70, 100, 50, 40);
    buttons[5].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(5);
    text1.setText(sb.toString());
    }

    });
    buttons[6].setBounds(130, 100, 50, 40);
    buttons[6].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(6);
    text1.setText(sb.toString());
    }

    });
    buttons[7].setBounds(190, 100, 50, 40);
    buttons[7].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(7);
    text1.setText(sb.toString());
    }

    });
    buttons[8].setBounds(10, 150, 50, 40);
    buttons[8].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(8);
    text1.setText(sb.toString());
    }

    });
    buttons[9].setBounds(70, 150, 50, 40);
    buttons[9].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(9);
    text1.setText(sb.toString());
    }

    });
    buttons[10].setBounds(130, 150, 50, 40);
    buttons[10].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sign = "+";
    no1 = text1.getText();
    sb.delete(0, sb.capacity());

    }
    });
    buttons[11].setBounds(190, 150, 50, 40);
    buttons[11].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sign = "-";
    no1 = text1.getText();
    sb.delete(0, sb.capacity());

    }
    });
    buttons[12].setBounds(10, 200, 50, 40);
    buttons[12].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sign = "*";
    no1 = text1.getText();
    sb.delete(0, sb.capacity());

    }
    });
    buttons[13].setBounds(70, 200, 50, 40);
    buttons[13].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sign = "/";
    no1 = text1.getText();
    sb.delete(0, sb.capacity());

    }
    });
    buttons[14].setForeground(Color.RED);
    buttons[14].setBounds(130, 200, 50, 40);
    buttons[14].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    int sum = 0;//最终结果
    if (sign.equals("+")) {
    int no2 = Integer.parseInt(no1);//取得前一个数

    int no3 = Integer.parseInt(text1.getText());//取得现在的数

    sum = no2 + no3;//累加

    text1.setText(String.valueOf(sum));

    }
    if (sign.equals("-")) {
    int no2 = Integer.parseInt(no1);

    int no3 = Integer.parseInt(text1.getText());

    sum = no2 - no3;

    text1.setText(String.valueOf(sum));

    }
    if (sign.equals("*")) {
    int no2 = Integer.parseInt(no1);

    int no3 = Integer.parseInt(text1.getText());

    sum = no2 * no3;

    text1.setText(String.valueOf(sum));

    }

    if (sign.equals("/")) {
    int no2 = Integer.parseInt(no1);

    int no3 = Integer.parseInt(text1.getText());

    sum = no2 / no3;

    text1.setText(String.valueOf(sum));

    }

    }

    });
    buttons[15].setBounds(190, 200, 50, 40);
    buttons[15].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.delete(0, sb.capacity());//清除sb的内容
    text1.setText("");//结果框设置为空
    }
    });

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//响应关闭窗口
    setVisible(true);//显示窗口
    }
    }

    2.主程序类
    package Calc;

    public class CalcTest {

    public static void main(String[] args) {
    CalcFrame f = new CalcFrame();

    }

    }



学习Java就到IT学习联盟

8. 怎么用java做个简单的计算器

package com.gjq.test;

import java.util.Scanner;

public class xte {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("****************计算器****************");

System.out.print("请输入数字①:");
Scanner scanner1 = new Scanner(System.in);
double num1= scanner1.nextDouble();

System.out.print("请输入运算符,如:+ - * /:");
Scanner scanner2 = new Scanner(System.in);
String zifu= scanner2.next();

System.out.print("请输入数字②:");
Scanner scanner3 = new Scanner(System.in);
double num3= scanner3.nextDouble();

char charzf =zifu.toCharArray()[0];
switch (charzf) {
case '+':
System.out.println("结果为:"+num1+" "+charzf+" "+num3+" = "+(num1+num3));
break;
case '-':
System.out.println("结果为:"+num1+" "+charzf+" "+num3+" = "+(num1-num3));
break;
case '*':
System.out.println("结果为:"+num1+" "+charzf+" "+num3+" = "+(num1*num3));
break;
case '/':
if(num3!=0){
System.out.println("结果为:"+num1+" "+charzf+" "+num3+" = "+(num1/num3));
}
break;
default:
System.out.println("输入错误!");
break;
}

}

}

热点内容
天墓密码结局是什么 发布:2025-02-09 05:25:52 浏览:437
如何找回因特网帐号的密码 发布:2025-02-09 05:20:05 浏览:373
树莓派源码 发布:2025-02-09 05:07:00 浏览:651
安卓手机为什么搜不到懂球帝 发布:2025-02-09 05:04:42 浏览:817
生命密码解读走什么 发布:2025-02-09 04:55:51 浏览:279
python常用正则表达式 发布:2025-02-09 04:42:53 浏览:179
机器人编程培训哪家好 发布:2025-02-09 04:37:44 浏览:308
上海怎么学习java 发布:2025-02-09 04:26:39 浏览:23
erp系统搭建备用服务器 发布:2025-02-09 04:07:38 浏览:946
戴尔服务器在bios怎么配置管理ip 发布:2025-02-09 04:01:53 浏览:551