2024年9月java实现简单的加减乘除(java的加减乘除运算)

 更新时间:2024-09-21 08:22:14

  ⑴java实现简单的加减乘除(java的加减乘除运算

  ⑵java的加减乘除运算

  ⑶使用BigDecimal并且一定要用String来够造。实现方法如下:importjava.math.BigDecimal;/***由于Java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精*确的浮点数运算,包括加减乘除和四舍五入。*/publilassArith{//默认除法运算精度privatestaticfinalintDEF_DIV_SCALE=;//这个类不能实例化privateArith(){}/***提供精确的加法运算。*paramv被加数*paramv加数*return两个参数的和*/publicstaticdoubleadd(doublev,doublev){BigDecimalb=newBigDecimal(Double.toString(v));BigDecimalb=newBigDecimal(Double.toString(v));returnb.add(b).doubleValue();}/***提供精确的减法运算。*paramv被减数*paramv减数*return两个参数的差*/publicstaticdoublesub(doublev,doublev){BigDecimalb=newBigDecimal(Double.toString(v));BigDecimalb=newBigDecimal(Double.toString(v));returnb.subtract(b).doubleValue();}/***提供精确的乘法运算。*paramv被乘数*paramv乘数*return两个参数的积*/publicstaticdoublemul(doublev,doublev){BigDecimalb=newBigDecimal(Double.toString(v));BigDecimalb=newBigDecimal(Double.toString(v));returnb.multiply(b).doubleValue();}/***提供(相对精确的除法运算,当发生除不尽的情况时,精确到*小数点以后位,以后的数字四舍五入。*paramv被除数*paramv除数*return两个参数的商*/publicstaticdoublediv(doublev,doublev){returndiv(v,v,DEF_DIV_SCALE);}/***提供(相对精确的除法运算。当发生除不尽的情况时,由scale参数指*定精度,以后的数字四舍五入。*paramv被除数*paramv除数*paramscale表示表示需要精确到小数点以后几位。*return两个参数的商*/publicstaticdoublediv(doublev,doublev,intscale){if(scale《){thrownewIllegalArgumentException(“Thescalemustbeapositiveintegerorzero“);}BigDecimalb=newBigDecimal(Double.toString(v));BigDecimalb=newBigDecimal(Double.toString(v));returnb.divide(b,scale,BigDecimal.ROUND_HALF_UP).doubleValue();}/***提供精确的小数位四舍五入处理。*paramv需要四舍五入的数字*paramscale小数点后保留几位*return四舍五入后的结果*/publicstaticdoubleround(doublev,intscale){if(scale《){thrownewIllegalArgumentException(“Thescalemustbeapositiveintegerorzero“);}BigDecimalb=newBigDecimal(Double.toString(v));BigDecimalone=newBigDecimal(““);returnb.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();}};

  ⑷求简单java写计算器代码加减乘除

  ⑸importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;publilassCalculatorextendsJFrameimplementsActionListener{privatebooleandotExist,operated,equaled;//帮助运算的布尔变量privatedoublestoredNumber;//目前的结果privatecharlastOperator;//表示上一运算符privateJTextFieldoperation;//结果栏privateJButtondot,plus,minus,multi,div,sqrt,equal,changePN,clear;//运算符privateJButtonnumbers;//数字//构造者publialculator(){setTitle(“Calculator“);//初始化变量dotExist=false;//表示当前的数是否有小数点operated=false;//表示任意运算符是否被按下equaled=false;//表示等号是否被按下storedNumber=;lastOperator=’?’;//初始化窗口变量operation=newJTextField(““);operation.setEditable(false);numbers=newJButton;for(inti=;i《;i++)numbers=newJButton(““+i);dot=newJButton(“.“);plus=newJButton(“+“);minus=newJButton(“-“);multi=newJButton(“*“);div=newJButton(“/“);sqrt=newJButton(“√“);equal=newJButton(“=“);changePN=newJButton(“±“);clear=newJButton(“AC“);//将窗口物体放入窗口GridBagLayoutlayout=newGridBagLayout();getContentPane().setLayout(layout);addponent(layout,operation,,,,);addponent(layout,numbers,,,,);addponent(layout,numbers,,,,);addponent(layout,numbers,,,,);addponent(layout,numbers,,,,);addponent(layout,numbers,,,,);addponent(layout,numbers,,,,);addponent(layout,numbers,,,,);addponent(layout,numbers,,,,);addponent(layout,numbers,,,,);addponent(layout,dot,,,,);addponent(layout,numbers,,,,);addponent(layout,sqrt,,,,);addponent(layout,plus,,,,);addponent(layout,minus,,,,);addponent(layout,multi,,,,);addponent(layout,div,,,,);addponent(layout,equal,,,,);addponent(layout,changePN,,,,);addponent(layout,clear,,,,);}//对按钮进行反应的方法publicvoidactionPerformed(ActionEvente){JButtonbtn=(JButton)e.getSource();if(btn==clear){operation.setText(““);dotExist=false;storedNumber=;lastOperator=’?’;}elseif(btn==equal){operate(’=’);equaled=true;}elseif(btn==plus){operate(’+’);equaled=false;}elseif(btn==minus){operate(’-’);equaled=false;}elseif(btn==multi){operate(’*’);equaled=false;}elseif(btn==div){operate(’/’);equaled=false;}elseif(btn==changePN){operate(’p’);operate(’=’);equaled=true;}elseif(btn==sqrt){operate(’s’);operate(’=’);equaled=true;}else{if(equaled)storedNumber=;for(inti=;i《;i++)if(btn==numbers){if(operation.getText().equals(““))operation.setText(““+i);elseif(!operated)operation.setText(operation.getText()+i);else{operation.setText(““+i);operated=false;}}if(btn==dot&&!dotExist){operation.setText(operation.getText()+“.“);dotExist=true;}}}//进行运算的方法privatevoidoperate(charoperator){doublecurrentNumber=Double.valueOf(operation.getText()).doubleValue();if(lastOperator==’?’)storedNumber=currentNumber;elseif(lastOperator==’+’)storedNumber+=currentNumber;elseif(lastOperator==’-’)storedNumber-=currentNumber;elseif(lastOperator==’*’)storedNumber*=currentNumber;elseif(lastOperator==’/’)storedNumber/=currentNumber;elseif(lastOperator==’p’)storedNumber*=-;elseif(lastOperator==’s’)storedNumber=Math.sqrt(currentNumber);elseif(lastOperator==’=’&&equaled)storedNumber=currentNumber;operation.setText(““+storedNumber);operated=true;lastOperator=operator;}//快捷使用GridBagLayout的方法privatevoidaddponent(GridBagLayoutlayout,ponentponent,introw,intcol,intwidth,intheight){GridBagConstraintsconstraints=newGridBagConstraints();constraints.fill=GridBagConstraints.BOTH;constraints.insets=newInsets(,,,);constraints.weightx=;constraints.weighty=;constraints.gridx=col;constraints.gridy=row;constraints.gridwidth=width;constraints.gridheight=height;layout.setConstraints(ponent,constraints);if(ponentinstanceofJButton)((JButton)ponent).addActionListener(this);getContentPane().add(ponent);}//主方法初始化并显示窗口publicstaticvoidmain(Stringargs){Calculatorcalc=newCalculator();calc.setSize(,);calc.setVisible(true);}}

  ⑹Java实现有界面的简单的两个整数之间的加减乘除运算

  ⑺这个必须通过swing技术实现,先看下效果图:

  ⑻import?java.awt.BorderLayout;import?java.awt.Color;import?java.awt.GridLayout;import?java.awt.event.ActionEvent;import?java.awt.event.ActionListener;import?javax.swing.ImageIcon;import?javax.swing.JButton;import?javax.swing.JFrame;import?javax.swing.JPanel;import?javax.swing.JTextField;import?javax.swing.SwingConstants;public?class?Jisuanqi?extends?JFrame?implements?ActionListener?{/**?*??*/private?static?final?long?serialVersionUID?=?L;Result?result?=?new?Result();?//?定义text的面板Number_Key?number_key?=?new?Number_Key();?//?定义按钮面板//?当点击按钮+、-、*、/时,?=?trueboolean??=?false;//?当i=时说明是我们第一次输入,字符串text不会累加int?i?=?;//?存放text的内容String?text?=?““;//?存放点击按钮+、-、*、/之前的数值double?defbutton?=?;//?+、-、*、/的代号分别为,,,int?symbol?=?;//?构造函数Jisuanqi()?{super(“WangJiao“);?//?设定标题setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);?//?设定关闭窗体时退出程序JPanel?pane?=?new?JPanel();?//?定义主面板pane.setLayout(new?BorderLayout());setBounds(,?,?,?);?//?前两个参数是在屏幕上显示的坐标,后两个是大小//?替换图标ImageIcon?icon?=?new?ImageIcon(“F:.GIF“);//?Jisuanqi.class.getResource(“APPLE.GIF“)//?);setIconImage(icon.getImage());pane.add(result,?BorderLayout.NORTH);pane.add(number_key,?BorderLayout.CENTER);pane.add(number_key.equal,?BorderLayout.SOUTH);number_key.one.addActionListener(this);?//?对按钮添加监听事件number_key.two.addActionListener(this);?//?对按钮添加监听事件number_key.three.addActionListener(this);?//?对按钮添加监听事件number_key.four.addActionListener(this);?//?对按钮添加监听事件number_key.five.addActionListener(this);?//?对按钮添加监听事件number_key.six.addActionListener(this);?//?对按钮添加监听事件number_key.seven.addActionListener(this);?//?对按钮添加监听事件number_key.eight.addActionListener(this);?//?对按钮添加监听事件number_key.nine.addActionListener(this);?//?对按钮添加监听事件number_key.zero.addActionListener(this);?//?对按钮添加监听事件number_key.ce.addActionListener(this);?//?对置零按钮添加监听事件number_key.plus.addActionListener(this);?//?对+按钮添加监听事件number_key.equal.addActionListener(this);?//?对=按钮添加监听事件number_key.sub.addActionListener(this);?//?对-按钮添加监听事件number_key.mul.addActionListener(this);?//?对*按钮添加监听事件number_key.div.addActionListener(this);?//?对/按钮添加监听事件number_key.point.addActionListener(this);?//?对.按钮添加监听事件setContentPane(pane);pack();?//?初始化窗体大小为正好盛放所有按钮}//?各个按钮触发的事件public?void?actionPerformed(ActionEvent?e)?{/*?*?如果是点击数字按钮那么先要判断是否在此之前点击了+、-、*、/、=,如果是那么=true?如果没有=?*?false;或者是否点击数字键,如果是i?=?,如果没有?i?=?;?*/if?(e.getSource()?==?number_key.one)?{if?(?||?i?==?)?{result.text.setText(““);?=?false;i?=?;}?else?{text?=?result.text.getText();result.text.setText(text?+?““);}}?else?if?(e.getSource()?==?number_key.two)?{if?(?||?i?==?)?{result.text.setText(““);?=?false;i?=?;}?else?{text?=?result.text.getText();result.text.setText(text?+?““);}}?else?if?(e.getSource()?==?number_key.three)?{if?(?||?i?==?)?{result.text.setText(““);?=?false;i?=?;}?else?{text?=?result.text.getText();result.text.setText(text?+?““);}}?else?if?(e.getSource()?==?number_key.four)?{if?(?||?i?==?)?{result.text.setText(““);?=?false;i?=?;}?else?{text?=?result.text.getText();result.text.setText(text?+?““);}}?else?if?(e.getSource()?==?number_key.five)?{if?(?||?i?==?)?{result.text.setText(““);?=?false;i?=?;}?else?{text?=?result.text.getText();result.text.setText(text?+?““);}}?else?if?(e.getSource()?==?number_key.six)?{if?(?||?i?==?)?{result.text.setText(““);?=?false;i?=?;}?else?{text?=?result.text.getText();result.text.setText(text?+?““);}}?else?if?(e.getSource()?==?number_key.seven)?{if?(?||?i?==?)?{result.text.setText(““);?=?false;i?=?;}?else?{text?=?result.text.getText();result.text.setText(text?+?““);}}?else?if?(e.getSource()?==?number_key.eight)?{if?(?||?i?==?)?{result.text.setText(““);?=?false;i?=?;}?else?{text?=?result.text.getText();result.text.setText(text?+?““);}}?else?if?(e.getSource()?==?number_key.nine)?{if?(?||?i?==?)?{result.text.setText(““);?=?false;i?=?;}?else?{text?=?result.text.getText();result.text.setText(text?+?““);}}/*?*?对于这个按钮有一定的说法,在我的程序里不会出现如这样的情况,我加了判断条件就是?*?如果text中的数值=就要判断在这个数值中是否有.存在?如果有那么就在原来数值基础之上添?加;否则保持原来的数值不变?*/else?if?(e.getSource()?==?number_key.zero)?{?//?result.text.getText()是得到text里内容的意思if?(?||?i?==?)?{result.text.setText(““);?=?false;i?=?;}?else?{text?=?result.text.getText();if?(Float.parseFloat(text)?》??||?Float.parseFloat(text)?《?)?{?//?Float.parseFloat(text)就是类型转换了,下面都是一样result.text.setText(text?+?““);}?else?{if?(text.trim().indexOf(“.“)?==?-)?{result.text.setText(text);}?else?{result.text.setText(text?+?““);}}}}?else?if?(e.getSource()?==?number_key.ce)?{result.text.setText(““);i?=?;?=?true;//?text?=?““;defbutton?=?;}/*?*?本程序不会让一个数值中出现个以上的小数点.具体做法是:判断是否已经存在.存在就不添加,?不存在就添加.?*/else?if?(e.getSource()?==?number_key.point)?{if?(?||?i?==?)?{result.text.setText(“.“);?=?false;i?=?;}?else?{text?=?result.text.getText();if?(text.trim().indexOf(“.“)?==?-)?{result.text.setText(text?+?“.“);}?else?{result.text.setText(text);}}}?//?获得点击+之前的数值else?if?(e.getSource()?==?number_key.plus)?{?=?true;i?=?;defbutton?=?Double.parseDouble(result.text.getText());symbol?=?;}?//?获得点击-之前的数值else?if?(e.getSource()?==?number_key.sub)?{?=?true;i?=?;defbutton?=?Double.parseDouble(result.text.getText());symbol?=?;}?//?获得点击*之前的数值else?if?(e.getSource()?==?number_key.mul)?{?=?true;i?=?;defbutton?=?Double.parseDouble(result.text.getText());System.out.println(defbutton);symbol?=?;}?//?获得点击/之前的数值else?if?(e.getSource()?==?number_key.div)?{?=?true;i?=?;defbutton?=?Double.parseDouble(result.text.getText());symbol?=?;}?else?if?(e.getSource()?==?number_key.equal)?{switch?(symbol)?{case?:?{?//?计算加法double?ad?=?defbutton+?Double.parseDouble(result.text.getText());result.text.setText(ad?+?““);i?=?;text?=?““;break;}case?:?{?//?计算减法double?ad?=?defbutton-?Double.parseDouble(result.text.getText());result.text.setText(String.valueOf(ad));i?=?;text?=?““;break;}case?:?{?//?计算乘法double?ad?=?defbutton*?Double.parseDouble(result.text.getText());result.text.setText(ad?+?““);i?=?;text?=?““;break;}case?:?{?//?计算除法double?ad?=?defbutton/?Double.parseDouble(result.text.getText());result.text.setText(ad?+?““);i?=?;text?=?““;break;}}System.out.println();}System.out.println(result.text.getText());}SuppressWarnings(“deprecation“)public?static?void?main(String?args)?{Jisuanqi?loveyou?=?new?Jisuanqi();loveyou.show();}}//?计算器数字按钮定义面板class?Number_Key?extends?JPanel?{/**?*??*/private?static?final?long?serialVersionUID?=?L;JButton?zero?=?new?JButton(““);?//?数字键JButton?one?=?new?JButton(““);?//?数字键JButton?two?=?new?JButton(““);?//?数字键JButton?three?=?new?JButton(““);?//?数字键JButton?four?=?new?JButton(““);?//?数字键JButton?five?=?new?JButton(““);?//?数字键JButton?six?=?new?JButton(““);?//?数字键JButton?seven?=?new?JButton(““);?//?数字键JButton?eight?=?new?JButton(““);?//?数字键JButton?nine?=?new?JButton(““);?//?数字键JButton?plus?=?new?JButton(“+“);JButton?sub?=?new?JButton(“-“);JButton?mul?=?new?JButton(“*“);JButton?div?=?new?JButton(“/“);JButton?equal?=?new?JButton(“=“);JButton?ce?=?new?JButton(“清零“);?//?置零键JButton?point?=?new?JButton(“.“);Number_Key()?{setLayout(new?GridLayout(,?,?,?));?//?定义布局管理器为网格布局setBackground(Color.blue);?//?设置背景颜色//?添加按钮add(one);add(two);add(three);add(four);add(five);add(six);add(seven);add(eight);add(nine);add(zero);add(plus);add(sub);add(mul);add(div);add(point);add(equal);add(ce);}}//?计算器显示结果的窗体class?Result?extends?JPanel?{/**?*??*/private?static?final?long?serialVersionUID?=?L;//?text先是输入和结果JTextField?text?=?new?JTextField(““);SuppressWarnings(“deprecation“)Result()?{?//?讲输入的数字或得到的结果在text的右边显示text.setHorizontalAlignment(SwingConstants.RIGHT);text.enable(false);?//?文本框不能setLayout(new?BorderLayout());?//?设定布局管理器边框布局add(text,?BorderLayout.CENTER);?//?text放置在窗体的中间}}

  ⑼java如何实现个个位数的加减乘除运算

  ⑽public?class?ParamDemo?{????public?static?void?main(String?args)?{????????Map《String,?Integer》?map?=?new?HashMap《》();????????map.put(“+“,?);????????map.put(“-“,?);????????map.put(“*“,?);????????map.put(“/“,?);????????Scanner?scanner?=?new?Scanner(System.in);????????int?num?=?scanner.nextInt();????????int?num?=?scanner.nextInt();????????int?num?=?scanner.nextInt();????????String?op?=?scanner.next();????????String?op?=?scanner.next();????????//此时证明第一个操作符优先级大于第二个操作符????????if?(map.get(op)?-?map.get(op)?》=?)?{????????????int?tmpNumber?=?operateNum(op,?num,?num);????????????System.out.println(operateNum(op,?tmpNumber,?num));????????}?else?{????????????int?tmpNumber?=?operateNum(op,?num,?num);????????????System.out.println(operateNum(op,?num,?tmpNumber));????????}????????scanner.close();????}????private?static?int?operateNum(String?operator,?int?num,?int?num)?{????????switch?(operator)?{????????????case?“+“:????????????????return?num?+?num;????????????case?“-“:????????????????return?num?-?num;????????????case?“*“:????????????????return?num?*?num;????????????case?“/“:????????????????return?num?/?num;????????????default:????????????????return?;????????}????}}

  ⑾java做一个简单的加减乘除运算,用键盘先后输入a,b的数值

  ⑿//参考下我刚写的这个,稍显得智能一些!你可以稍加更改;思路都注释的很详细了!//代码也不算多,import?java.util.Scanner;public?class?计算器?{private?static?Scanner?sc?=?new?Scanner(System.in);public?static?void?main(String?args)?{init();}private?static?void?init()?{while?(true)sop(input());}private?static?String?input()?{sop(“请输入运算表达式如:+回车!“);String?str?=?sc.nextLine(),?sum?=?““;char?tem?=?;int?poin?=?;for?(int?i?=?;?i?《?str.length();?i++)?{//遍历!char?cs?=?str.charAt(i);if?(cs?==?’+’?||?cs?==?’-’?||?cs?==?’*’?||?cs?==?’/’)?{//?寻找找运算符号tem?=?str.charAt(i);//?记录运算符号!poin?=?i;//?记录符号位置!break;}?else?if?(i?》=?str.length()?-?)?{sop(“输入不合法请检查!“);init();}}//?拆分数字!double?a?=?Double.parseDouble(str.substring(,?poin));double?b?=?Double.parseDouble(str.substring(poin?+?));switch?(tem)?{//?开始判断运算!case?’+’:sum?=?““?+?(a?+?b);break;case?’-’:sum?=?““?+?(a?-?b);break;case?’*’:sum?=?““?+?(a?*?b);break;default:sum?=?““?+?(a?/?b);break;}return?str?+?“=“?+?sum;}//打印功能!private?static?void?sop(Object?obj)?{System.out.println(obj);}}

  ⒀java加减乘除运算的程序怎么编啊

  ⒁//JAVA编程:四则运算(接收用户输入的个操作数,和运算符),计算之后,输出结果~~~~importjava.util.Scanner;publilass四则运算{publicstaticvoidmain(Stringargs){Scannersc=newScanner(System.in);System.out.print(“请输入第一个数字:“);inta=sc.nextInt();System.out.print(“请输入运算符号:“);Stringstr=sc.next();charch=str.charAt();System.out.print(“请输入第二个数字:“);intb=sc.nextInt();switch(ch){case’+’:System.out.println(a+“+“+b+“=“+(a+b));break;case’-’:System.out.println(a+“-“+b+“=“+(a-b));break;case’*’:System.out.println(a+“*“+b+“=“+(a*b));break;case’/’:if(b==){System.out.println(“被除数为零,运算无意义!“);break;}else{System.out.println(a+“/“+b+“=“+(a/b));break;}default:System.out.println(“运算符是无意义字符!“);break;}}}望采纳~~~~~~~~

  ⒂JAVA制作一个简单的计算器能实现两个数的加、减、乘、除四则运算

  ⒃import?java.util.*;import?java.awt.*;import?java.awt.event.*;import?javax.swing.*;import?java.applet.*;public?class?Demo?extends?JApplet?implements?ActionListener?{boolean?i?=?true;private?JButton?num?=?new?JButton(““);private?JButton?num?=?new?JButton(““);private?JButton?num?=?new?JButton(““);private?JButton?num?=?new?JButton(““);private?JButton?num?=?new?JButton(““);private?JButton?num?=?new?JButton(““);private?JButton?num?=?new?JButton(““);private?JButton?num?=?new?JButton(““);private?JButton?num?=?new?JButton(““);private?JButton?num?=?new?JButton(““);private?JButton?zuok?=?new?JButton(“(“);private?JButton?youk?=?new?JButton(“)“);private?JButton?dian?=?new?JButton(“.“);private?JButton?NULL?=?new?JButton(“N“);private?JButton?plu?=?new?JButton(“+“);private?JButton?min?=?new?JButton(“-“);private?JButton?mul?=?new?JButton(“x“);private?JButton?div?=?new?JButton(“/“);private?JButton?equ?=?new?JButton(“=“);private?JButton?cle?=?new?JButton(“C“);//?清除private?JTextField?space?=?new?JTextField();public?void?init()?{JPanel?text?=?new?JPanel();text.setLayout(new?FlowLayout());text.add(space);JPanel?buttons?=?new?JPanel();buttons.setLayout(new?GridLayout(,?));buttons.add(num);buttons.add(num);buttons.add(num);buttons.add(plu);buttons.add(num);buttons.add(num);buttons.add(num);buttons.add(min);buttons.add(num);buttons.add(num);buttons.add(num);buttons.add(mul);buttons.add(num);buttons.add(cle);buttons.add(equ);buttons.add(div);(num).addActionListener(this);(num).addActionListener(this);(num).addActionListener(this);(num).addActionListener(this);(num).addActionListener(this);(num).addActionListener(this);(num).addActionListener(this);(num).addActionListener(this);(num).addActionListener(this);(num).addActionListener(this);(plu).addActionListener(this);(min).addActionListener(this);(mul).addActionListener(this);(div).addActionListener(this);(equ).addActionListener(this);(cle).addActionListener(this);setLayout(new?BorderLayout());add(“North“,?text);add(“South“,?buttons);space.setText(““);}public?void?actionPerformed(ActionEvent?e)?{if?(e.getSource()?==?num)?{if?(i?==?true)?{space.setText(““);i?=?false;}?elsespace.setText(space.getText()?+?’’);}if?(e.getSource()?==?num)?{if?(i?==?true)?{space.setText(““);i?=?false;}?elsespace.setText(space.getText()?+?’’);}if?(e.getSource()?==?num)?{if?(i?==?true)?{space.setText(““);i?=?false;}?elsespace.setText(space.getText()?+?’’);}if?(e.getSource()?==?num)?{if?(i?==?true)?{space.setText(““);i?=?false;}?elsespace.setText(space.getText()?+?’’);}if?(e.getSource()?==?num)?{if?(i?==?true)?{space.setText(““);i?=?false;}?elsespace.setText(space.getText()?+?’’);}if?(e.getSource()?==?num)?{if?(i?==?true)?{space.setText(““);i?=?false;}?elsespace.setText(space.getText()?+?’’);}if?(e.getSource()?==?num)?{if?(i?==?true)?{space.setText(““);i?=?false;}?elsespace.setText(space.getText()?+?’’);}if?(e.getSource()?==?num)?{if?(i?==?true)?{space.setText(““);i?=?false;}?elsespace.setText(space.getText()?+?’’);}if?(e.getSource()?==?num)?{if?(i?==?true)?{space.setText(““);i?=?false;}?elsespace.setText(space.getText()?+?’’);}if?(e.getSource()?==?num)?{if?(i?==?true)?{space.setText(““);i?=?false;}?elsespace.setText(space.getText()?+?’’);}if?(e.getSource()?==?plu)?{space.setText(space.getText()?+?’+’);i?=?false;}if?(e.getSource()?==?min)?{space.setText(space.getText()?+?’-’);i?=?false;}if?(e.getSource()?==?mul)?{space.setText(space.getText()?+?’*’);i?=?false;}if?(e.getSource()?==?div)?{space.setText(space.getText()?+?’/’);i?=?false;}if?(e.getSource()?==?equ)?{space.setText(String.valueOf(Calculator(space.getText())));i?=?true;}if?(e.getSource()?==?cle)?{space.setText(““);i?=?true;}}public?double?Calculator(String?f)//?科学计算{int?i?=?,?j?=?,?k;char?c;StringBuffer?s?=?new?StringBuffer();s.append(f);s.append(’=’);String?formula?=?s.toString();char?anArray;anArray?=?new?char;Stack《Character》?mystack?=?new?Stack《Character》();while?(formula.charAt(i)?!=?’=’)?{c?=?formula.charAt(i);switch?(c)?{case?’+’:case?’-’:while?(!mystack.empty()?&&?mystack.peek().charValue()?!=?’(’)?{anArray?=?mystack.pop().charValue();}mystack.push(new?Character(c));i++;break;case?’*’:case?’/’:while?(!mystack.empty()&&?(mystack.peek().charValue()?==?’*’?||?mystack.peek().charValue()?==?’/’))?{anArray?=?mystack.pop().charValue();}mystack.push(new?Character(c));i++;break;case?’?’:i++;break;default:while?((c?》=?’’?&&?c?《=?’’)?||?c?==?’.’)?{anArray?=?c;i++;c?=?formula.charAt(i);}anArray?=?’#’;break;}}while?(!(mystack.empty()))anArray?=?mystack.pop().charValue();i?=?;int?count;double?a,?b,?d;Stack《Double》?mystack?=?new?Stack《Double》();while?(i?《?j)?{c?=?anArray;switch?(c)?{case?’+’:a?=?mystack.pop().doubleValue();b?=?mystack.pop().doubleValue();d?=?b?+?a;mystack.push(new?Double(d));i++;break;case?’-’:a?=?mystack.pop().doubleValue();b?=?mystack.pop().doubleValue();d?=?b?-?a;mystack.push(new?Double(d));i++;break;case?’*’:a?=?mystack.pop().doubleValue();b?=?mystack.pop().doubleValue();d?=?b?*?a;mystack.push(new?Double(d));i++;break;case?’/’:a?=?mystack.pop().doubleValue();b?=?mystack.pop().doubleValue();if?(a?!=?)?{d?=?b?/?a;mystack.push(new?Double(d));i++;}?else?{System.out.println(“Error!“);}break;default:d?=?;count?=?;while?((c?》=?’’?&&?c?《=?’’))?{d?=??*?d?+?c?-?’’;i++;c?=?anArray;}if?(c?==?’.’)?{i++;c?=?anArray;while?((c?》=?’’?&&?c?《=?’’))?{count++;d?=?d?+?(c?-?’’)?/?Math.pow(,?count);i++;c?=?anArray;}}if?(c?==?’#’)mystack.push(new?Double(d));i++;break;}}return?(mystack.peek().doubleValue());}}

  ⒄加减乘除运算(Java)

  ⒅实际上这相当于javascript的eval方法,以下是该方法的java实现://Eval.javaimportjava.util.ArrayList;importjava.util.List;importjava.util.Stack;publilassEval{publicinteval(Stringexp){List《String》list=infixExpToPostExp(exp);//转化成后缀表达式returndoEval(list);//真正求值}//遇到操作符压栈,遇到表达式从后缀表达式中弹出两个数,计算出结果,压入堆栈privateintdoEval(List《String》list){Stack《String》stack=newStack《String》();Stringelement;intn,n,result;try{for(inti=;i《list.size();i++){element=list.get(i);if(isOperator(element)){n=Integer.parseInt(stack.pop());n=Integer.parseInt(stack.pop());result=doOperate(n,n,element);stack.push(newInteger(result).toString());}else{stack.push(element);}}returnInteger.parseInt(stack.pop());}catch(RuntimeExceptione){thrownewIllegalExpressionException(e.getMessage());}}privateintdoOperate(intn,intn,Stringoperator){if(operator.equals(“+“))returnn+n;elseif(operator.equals(“-“))returnn-n;elseif(operator.equals(“*“))returnn*n;elsereturnn/n;}privatebooleanisOperator(Stringstr){returnstr.equals(“+“)||str.equals(“-“)||str.equals(“*“)||str.equals(“/“);}privateList《String》infixExpToPostExp(Stringexp){//将中缀表达式转化成为后缀表达式List《String》postExp=newArrayList《String》();//存放转化的后缀表达式的链表StringBuffernumBuffer=newStringBuffer();//用来保存一个数的Stack《Character》opStack=newStack《Character》();//操作符栈charch,preChar;opStack.push(’#’);try{for(inti=;i《exp.length();){ch=exp.charAt(i);switch(ch){case’+’:case’-’:case’*’:case’/’:preChar=opStack.peek();//如果栈里面的操作符优先级比当前的大,则把栈中优先级大的都添加到后缀表达式列表中while(priority(preChar)》=priority(ch)){postExp.add(““+preChar);opStack.pop();preChar=opStack.peek();}opStack.push(ch);i++;break;case’(’://左括号直接压栈opStack.push(ch);i++;break;case’)’://右括号则直接把栈中左括号前面的弹出,并加入后缀表达式链表中charc=opStack.pop();while(c!=’(’){postExp.add(““+c);c=opStack.pop();}i++;break;//#号,代表表达式结束,可以直接把操作符栈中剩余的操作符全部弹出,并加入后缀表达式链表中case’#’:charc;while(!opStack.isEmpty()){c=opStack.pop();if(c!=’#’)postExp.add(““+c);}i++;break;//过滤空白符case’’:case’ ’:i++;break;//数字则凑成一个整数,加入后缀表达式链表中default:if(Character.isDigit(ch)){while(Character.isDigit(ch)){numBuffer.append(ch);ch=exp.charAt(++i);}postExp.add(numBuffer.toString());numBuffer=newStringBuffer();}else{thrownewIllegalExpressionException(“illegaloperator“);}}}}catch(RuntimeExceptione){thrownewIllegalExpressionException(e.getMessage());}returnpostExp;}privateintpriority(charop){//定义优先级switch(op){case’+’:case’-’:return;case’*’:case’/’:return;case’(’:case’#’:return;}thrownewIllegalExpressionException(“Illegaloperator“);}}Main.java主函数所在类publilassMain{publicstaticvoidmain(Stringargs){try{InputStreamReaderisr=newInputStreamReader(System.in);BufferedReaderbr=newBufferedReader(isr);Stringexp=br.readLine();intresult=eval.eval(exp);System.out.println(result);}}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}IllegalExpressionException异常类publilassIllegalExpressionExceptionextendsRuntimeException{publicIllegalExpressionException(){}publicIllegalExpressionException(Stringinfo){super(info);}}

您可能感兴趣的文章:

相关文章