怎么用JAVA编程编写一个计算器

怎么用JAVA编程编写一个计算器,第1张

打开IED:打开自己java编程的软件,采用的是eclipse软件。

建立java工程。

编写类。

编写类的详细步骤

1类的基本结构:

由于这里用到了界面,所以要进行窗口界面的编程,按钮事件的处理,和计算处理界面;

package MyCaculator;

import javaawt;

import javaawtevent;

import javaxswing;

public class MyCaculator extends JFrame {

private int add=1,sub=2,mul=3,div=4;

private int op=0;

boolean ifOp;

private String output="0";

private Button[] jba=new Button[]{new Button("7"),new Button("8"),

new Button("9"),new Button("+"),

new Button("4"),new Button("5"),new Button("6"),new Button("-"),

new Button("1"),new Button("2"),new Button("3"),new Button(""),

new Button("0"),new Button(""),new Button("="),new Button("/")};

private JPanel jpt=new JPanel();

private JPanel jpb=new JPanel();

private JTextField jtf=new JTextField("");

private MyCaculator(){

}

private void operate(String x){

}

public String add(String x){

return output;

}

public String subtract(String x){

return output;

}

public String multiply(String x){

return output;

}

public String divide(String x){

return output;

}

public String Equals(String x){

return output;

}

public void opClean(){

}

class setOperate_Act implements ActionListener{

public void actionPerformed(ActionEvent e) {

}

}

class setLabel_Act implements ActionListener{

public void actionPerformed(ActionEvent e) {

}

}

public static void main(String[] args) {

}

}

2建立构造方法

所谓构造方法就是,对自己的主类进行初始化,代码如下:

private MyCaculator(){

jptsetLayout(new BorderLayout());

jptadd(jtf);

thisadd(jpt,BorderLayoutNORTH);

jpbsetLayout(new GridLayout(4,4));

for(int i=0;i<jbalength;i++){

jpbadd(jba[i]);

if(i==3||i==7||i==11||i==15||i==14)

jba[i]addActionListener(new setOperate_Act());

else

jba[i]addActionListener(new setLabel_Act());

}

thisadd(jpb,BorderLayoutCENTER);

thissetSize(250, 200);

thissetResizable(false);

thissetVisible(true);

thissetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

}

3建立数据计算方法

这里的数据计算方法有6个,一个是主方法其他几个是加减乘除的处理方法,代码如下:

private void operate(String x){

double x1=DoublevalueOf(x);

double y=DoublevalueOf(output);

switch(op){

case 0:output=x;break;

case 1:output=StringvalueOf(y+x1);break;

case 2:output =StringvalueOf(y-x1);break;

case 3:output =StringvalueOf(yx1);break;

case 4:

if(x1!=0) output=StringvalueOf(y/x1);

else output="不能为0";

break;

}

}

public String add(String x){

operate(x);

op=add;

return output;

}

public String subtract(String x){

operate(x);

op=sub;

return output;

}

public String multiply(String x){

operate(x);

op=mul;

return output;

}

public String divide(String x){

operate(x);

op=div;

return output;

}

public String Equals(String x){

operate(x);

op=0;

return output;

}

public void opClean(){

op=0;

output ="0";

}

4事件处理方法

这里的时间处理方法,没有建立一个整体的方法,二是在为了便于处理的方法,将按钮事件分成两个部分,并采用两个子类来实现,这两个类时内部类要写在主类内部的,代码如下:

class setOperate_Act implements ActionListener{

public void actionPerformed(ActionEvent e) {

if(egetSource()==jba[3]){

jtfsetText(add(jtfgetText()));

ifOp=true;

}

else if(egetSource()==jba[7]){

jtfsetText(subtract(jtfgetText()));

ifOp=true;

}

else if(egetSource()==jba[11]){

jtfsetText(multiply(jtfgetText()));

ifOp=true;

}

else if(egetSource()==jba[15]){

jtfsetText(divide(jtfgetText()));

ifOp=true;

}

else if(egetSource()==jba[14]){

jtfsetText(Equals(jtfgetText()));

ifOp=true;

}

}

}

class setLabel_Act implements ActionListener{

public void actionPerformed(ActionEvent e) {

Button tempb=(Button)egetSource();

if(ifOp){

jtfsetText(tempbgetLabel());

ifOp=false;

}else {

jtfsetText(jtfgetText()+tempbgetLabel());

}

}

}

5建立main方法:

要想实现我们的代码,我们需在main方法中,实例化我们的对象。

public static void main(String[] args) {

new MyCaculator();

}

package com;

import javaxswing;

import javaawt;

import javaawtevent;

public class Calculator extends JFrame implements ActionListener{

private static final long serialVersionUID = 8199443193151152362L;

private JButton bto_s=new JButton("sqrt"),bto_zf=new JButton("+/-"),bto_ce=new JButton("CE"),bto_c=new JButton("C"),bto_7=new JButton("7"),

bto_8=new JButton("8"),bto_9=new JButton("9"),bto_chu=new JButton("/"),bto_4=new JButton("4"),bto_5=new JButton("5"),

bto_6=new JButton("6"),bto_cheng=new JButton(""),bto_1=new JButton("1"),bto_2=new JButton("2"),bto_3=new JButton("3"),

bto_jian=new JButton("-"),bto_0=new JButton("0"),bto_dian=new JButton(""),bto_deng=new JButton("="),bto_jia=new JButton("+");

JButton button[]={bto_s,bto_zf,bto_ce,bto_c,bto_7,bto_8,bto_9,bto_chu,bto_4,bto_5,bto_6,bto_cheng,bto_1,bto_2,bto_3,bto_jian,

bto_0,bto_dian,bto_deng,bto_jia};

private JTextField text_double;// = new JTextField("0");

private String operator = "="; //当前运算的运算符

private boolean firstDigit = true; // 标志用户按的是否是整个表达式的第一个数字,或者是运算符后的第一个数字

private double resultNum = 00; // 计算的中间结果

private boolean operateValidFlag = true; //判断 *** 作是否合法

private JLabel stuno = new JLabel("计算器"); //学号

private JLabel stuname = new JLabel("计算器"); //姓名

public Calculator()

{

super("Calculator");

thissetBounds(300, 300, 300, 320);

thissetResizable(false);

thissetBackground(Colororange);

thissetDefaultCloseOperation(EXIT_ON_CLOSE);

thisgetContentPane()setLayout(new BorderLayout());//设置布局

JPanel topPanel = new JPanel(new BorderLayout());

topPaneladd(stuno,BorderLayoutWEST);

topPaneladd(stuname,BorderLayoutEAST);

text_double=new JTextField("0",20);//设置文本区

text_doublesetHorizontalAlignment(JTextFieldRIGHT);//设置水平对齐方式未右对齐

topPaneladd(text_double,BorderLayoutSOUTH);

thisgetContentPane()add(topPanel,BorderLayoutNORTH);//将文本区添加到Content北部

JPanel panel=new JPanel(new GridLayout(5,4));//在内容窗口添加一个网格布局

thisgetContentPane()add(panel);//添加panel面板

for(int i=0;i<buttonlength;i++)//在面板上添加按钮

paneladd(button[i]);

for(int i=0;i<buttonlength;i++)

button[i]addActionListener(this);//为按钮注册

text_doublesetEditable(false);//文本框不可编辑

text_doubleaddActionListener(this);//

thissetVisible(true);

}

public void actionPerformed(ActionEvent e)//

{

String c= egetActionCommand();//返回与此动作相关的命令字符串。

Systemoutprintln("##########command is "+c);

if(cequals("C")){

handleC(); //用户按了“C”键

}

else if (cequals("CE")) // 用户按了"CE"键

{

text_doublesetText("0");

}

else if ("0123456789"indexOf(c) >= 0) // 用户按了数字键或者小数点

{

handleNumber(c); // handlezero(zero);

} else //用户按了运算符键

{

handleOperator(c);

}

}

private void handleC() // 初始化计算器的各种值

{

text_doublesetText("0");

firstDigit = true;

operator = "=";

}

private void handleNumber(String button) {

if (firstDigit)//输入的第一个数字

{

text_doublesetText(button);

} else if ((buttonequals("")) && (text_doublegetText()indexOf("") < 0))//输入的是小数点,并且之前没有小数点,则将小数点附在结果文本框的后面

//如果字符串参数作为一个子字符串在此对象中出现,则返回第一个这种子字符串的第一个字符的索引;如果它不作为一个子字符串出现,则返回 -1

{

text_doublesetText(text_doublegetText() + "");

} else if (!buttonequals(""))// 如果输入的不是小数点,则将数字附在结果文本框的后面

{

text_doublesetText(text_doublegetText() + button);

}

// 以后输入的肯定不是第一个数字了

firstDigit = false;

}

private void handleOperator(String button) {

if (operatorequals("/")) {

// 除法运算

// 如果当前结果文本框中的值等于0

if (getNumberFromText() == 00){

// *** 作不合法

operateValidFlag = false;

text_doublesetText("除数不能为零");

} else {

resultNum /= getNumberFromText();

}

} else if (operatorequals("+")){

// 加法运算

resultNum += getNumberFromText();

} else if (operatorequals("-")){

// 减法运算

resultNum -= getNumberFromText();

} else if (operatorequals("")){

// 乘法运算

resultNum = getNumberFromText();

} else if (operatorequals("sqrt")) {

// 平方根运算

if(getNumberFromText()<0){

operateValidFlag = false;

text_doublesetText("被开方数不能为负数");}

else

resultNum = Mathsqrt(resultNum);

}

else if (operatorequals("+/-")){

// 正数负数运算

resultNum = resultNum (-1);

} else if (operatorequals("=")){

// 赋值运算

resultNum = getNumberFromText();

}

if (operateValidFlag) {

// 双精度浮点数的运算

long t1;

double t2;

t1 = (long) resultNum;

t2 = resultNum - t1;

if (t2 == 0) {

text_doublesetText(StringvalueOf(t1));

} else {

text_doublesetText(StringvalueOf(resultNum));

}

}

operator = button; //运算符等于用户按的按钮

firstDigit = true;

operateValidFlag = true;

}

private double getNumberFromText() //从结果的文本框获取数字

{

double result = 0;

try {

result = DoublevalueOf(text_doublegetText())doubleValue(); // ValueOf()返回表示指定的 double 值的 Double 实例

} catch (NumberFormatException e){

}

return result;

}

public static void main(final String[] args) {

new Calculator();

}

}

public class Number {

private Integer n1;

private Integer n2;

/ 构造方法 /

public Number(Integer n1, Integer n2) {

super();

thisn1 = n1;

thisn2 = n2;

}

/ 加 /

public Integer addition() {

Systemoutprintln(thisn1 + thisn2);

return thisn1 + thisn2;

}

/ 减 /

public Integer subtration() {

Systemoutprintln(thisn1 - thisn2);

return thisn1 - thisn2;

}

/ 乘 /

public Integer multiplication() {

Systemoutprintln(thisn1 thisn2);

return thisn1 thisn2;

}

/ 除 /

public Integer division() {

Systemoutprintln(thisn1 / thisn2);

return thisn1 / thisn2;

}

public Integer getN1() {

return n1;

}

public void setN1(Integer n1) {

thisn1 = n1;

}

public Integer getN2() {

return n2;

}

public void setN2(Integer n2) {

thisn2 = n2;

}

}

public static void main(String[] args) {

Number number = new Number(1, 2);

numberaddition();

numbersubtration();

numbermultiplication();

numberdivision();

}

package swing;

import javaawt;

import javaawtevent;

import javaxswing;

@SuppressWarnings("serial")

public class Calculator extends JFrame{

JTextField jt1 ,jt2 ,jt3;

JLabel jLabel;

JButton equButton,addButton,reduceButton,mulButton,divButton;

public Calculator() {

super("简易计算器");

JPanel contentPanel = new JPanel();

contentPanelsetLayout(new GridLayout(2, 0));

JPanel uJPanel = new JPanel();

Dimension preferredSize = new Dimension(50, 29);

GridBagConstraints gbc = new GridBagConstraints();

uJPanelsetLayout(new GridBagLayout());

gbcgridx = GridBagConstraintsRELATIVE;

gbcgridy = 0;

gbcfill = GridBagConstraintsHORIZONTAL;

gbcinsets = new Insets(1, 2, 1, 2);

jt1 = new JTextField(4);

jLabel = new JLabel();

jLabelsetPreferredSize(new Dimension(10, 29));

jt2 = new JTextField(4);

equButton = new JButton("=");

ActionListener myActionListener = new MyActionListener();

equButtonaddActionListener(myActionListener);

jt3 = new JTextField(8);

jt1setPreferredSize(preferredSize);

jt2setPreferredSize(preferredSize);

jt3setPreferredSize(preferredSize);

uJPaneladd(jt1,gbc);

uJPaneladd(jLabel,gbc);

uJPaneladd(jt2,gbc);

uJPaneladd(equButton,gbc);

gbcweightx = 1;

uJPaneladd(jt3,gbc);

contentPaneladd(uJPanel);

JPanel dJPanel = new JPanel();

dJPanelsetLayout(new FlowLayout(FlowLayoutCENTER, 8, 2));

addButton = new JButton("+");

reduceButton = new JButton("-");

mulButton = new JButton("");

divButton = new JButton("/");

addButtonaddActionListener(myActionListener);

reduceButtonaddActionListener(myActionListener);

mulButtonaddActionListener(myActionListener);

divButtonaddActionListener(myActionListener);

dJPaneladd(addButton);

dJPaneladd(reduceButton);

dJPaneladd(mulButton);

dJPaneladd(divButton);

contentPaneladd(dJPanel);

thissetContentPane(contentPanel);

thispack();

thissetLocationRelativeTo(null);

thissetDefaultCloseOperation(3);

thissetVisible(true);

}

class MyActionListener implements ActionListener{

Double d1,d2,d3;

String operator = "";

public void actionPerformed(ActionEvent e) {

String fun = egetActionCommand();

if (!funequals("=")) {

jLabelsetText(fun);

operator = fun;

}else {

d1 = jt1getText()equals("")null:DoublevalueOf(jt1getText());

d2 = jt2getText()equals("")null:DoublevalueOf(jt2getText());

d3 = calculate(d1,d2,operator);

jt3setText(d3==null  "":d3toString());

jt3setCaretPosition(0);

}

}

}

Double calculate(Double d1,Double d2,String operator){

if (d1 == null || d2 == null) {

return null;

}

Double d3 = null;

switch (operator) {

case "+":

d3 = d1 + d2;

break;

case "-":

d3 = d1 - d2;

break;

case "":

d3 = d1  d2;

break;

case "/":

d3 = d1 / d2;

break;

}

return d3;

}

public static void main(String[] args) {

new Calculator();

}

}

以上就是关于怎么用JAVA编程编写一个计算器全部的内容,包括:怎么用JAVA编程编写一个计算器、用JAVA写一个计算器 要求有图形界面。简单的加减乘除,不要小数点运算。、一、编写Java程序,模拟简单的计算器。等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zz/10043444.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-04
下一篇2023-05-04

发表评论

登录后才能评论

评论列表(0条)

    保存