导航:首页 > 编程语言 > java计算加减乘除

java计算加减乘除

发布时间:2022-08-24 21:10:46

‘壹’ 加减乘除运算(java)

实际上这相当于javascript的eval方法,以下是该方法的java实现:

//Eval.java
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Eval {
public int eval(String exp){
List<String> list = infixExpToPostExp(exp);//转化成后缀表达式
return doEval(list);//真正求值
}

//遇到操作符压栈,遇到表达式从后缀表达式中弹出两个数,计算出结果,压入堆栈
private int doEval(List<String> list) {
Stack<String> stack = new Stack<String>();
String element;
int n1,n2,result;
try{
for(int i = 0; i < list.size();i++){
element = list.get(i);
if(isOperator(element)){
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
result = doOperate(n1,n2,element);
stack.push(new Integer(result).toString());
}else{
stack.push(element);
}
}
return Integer.parseInt(stack.pop());
}catch(RuntimeException e){
throw new IllegalExpressionException(e.getMessage());
}
}

private int doOperate(int n1, int n2, String operator) {
if(operator.equals("+"))
return n1 + n2;
else if(operator.equals("-"))
return n1 - n2;
else if(operator.equals("*"))
return n1 * n2;
else
return n1 / n2;
}

private boolean isOperator(String str){
return str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/");
}

private List<String> infixExpToPostExp(String exp){//将中缀表达式转化成为后缀表达式
List<String> postExp = new ArrayList<String>();//存放转化的后缀表达式的链表
StringBuffer numBuffer = new StringBuffer();//用来保存一个数的
Stack<Character> opStack = new Stack<Character>();//操作符栈
char ch,preChar;
opStack.push('#');
try{
for(int i = 0; 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 ')':
// 右括号则直接把栈中左括号前面的弹出,并加入后缀表达式链表中
char c = opStack.pop();
while(c != '('){
postExp.add("" + c);
c = opStack.pop();
}
i++;
break;
// #号,代表表达式结束,可以直接把操作符栈中剩余的操作符全部弹出,并加入后缀表达式链表中
case '#':
char c1;
while(!opStack.isEmpty()){
c1 = opStack.pop();
if(c1 != '#')
postExp.add("" + c1);
}
i++;
break;
//过滤空白符
case ' ':
case '\t':
i++;
break;
// 数字则凑成一个整数,加入后缀表达式链表中
default:
if(Character.isDigit(ch)){
while(Character.isDigit(ch)){
numBuffer.append(ch);
ch = exp.charAt(++i);
}
postExp.add(numBuffer.toString());
numBuffer = new StringBuffer();
}else{
throw new IllegalExpressionException("illegal operator");
}
}
}
}catch(RuntimeException e){
throw new IllegalExpressionException(e.getMessage());
}
return postExp;
}

private int priority(char op){//定义优先级
switch(op){
case'+':
case'-':
return 1;
case'*':
case'/':
return 2;
case'(':
case'#':
return 0;
}
throw new IllegalExpressionException("Illegal operator");
}

}

Main.java 主函数所在类
public class Main
{
public static void main(String[] args) {

try {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String exp=br.readLine();

int result = eval.eval(exp);
System.out.println(result);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

IllegalExpressionException异常类
public class IllegalExpressionException extends RuntimeException{

public IllegalExpressionException(){

}

public IllegalExpressionException(String info){
super(info);
}
}

‘贰’ java中简单的加减乘除运算

在a.jsp中写如下代码:

请输入
<form action="b.jsp" method="post">
上课作业比率:<input type="text" name="zy" /> <br />
上课实训:<input type="text" name="sksx" /> <br />
平时考勤: <input type="text" name="kq" /> <br />
平时实训:<input type="text" name="pssx" /> <br />
</form>

b.jsp中..
<%String s = request.getParameter("zy")
//.......
%>

懒得写了太麻烦@_@

‘叁’ java加减乘除是什么类

java中实现加减乘除的类是java.math.BigDecimal类. BigDecimal 类提供以下操作:算术、标度操作、舍入、比较、哈希算法和格式转换。

加法运算:调用BigDecimal类的add方法即可

BigDecimalb1=newBigDecimal("1");
BigDecimalb2=newBigDecimal("2");
BigDecimalresult=b1.add(b2);//加法
System.out.println(result);

减法运算:调用BigDecimal类的subtract方法即可

BigDecimalb1=newBigDecimal(3.2);
BigDecimalb2=newBigDecimal(1.6);
BigDecimalresult=b1.subtract(b2);//减法
System.out.println(result);

乘法运算:调用BigDecimal类的multiply方法即可

BigDecimalb1=newBigDecimal(9);
BigDecimalb2=newBigDecimal(8.2);
BigDecimalresult=b1.multiply(b2);//乘法
System.out.println(result);

除法运算:调用BigDecimal类的divide方法即可。

注意: 除法运算存在除不尽的情况,比如1.0/3=0.333333.. 我们需要指定小数点后面的长度,以及有效的舍入模式(例如四舍五入模式).

BigDecimalb1=newBigDecimal("1");
BigDecimalb2=newBigDecimal("3");
intscale=5;//scale指定小数点后面的位数为5位
doubleresult=b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();//除法
//BigDecimal.ROUND_HALF_UP表示四舍五入
System.out.println(result);

备注:

1:BigDecimal的构造参数有很多,但浮点类型建议转换成字符串类型, 避免精度的丢失.

doubled1=0.001;//浮点类型
Strings1=Double.toString(d1);//转成字符串
BigDecimalb1=newBigDecimal(s1);//使用字符串作为构造参数

2:BigDecimal类, 内存占用比基本类型多,并且为了计算的精度,速度比double慢一点.所以,只有在需要精确计算的情况下,才使用BigDecimal类进行. 普通运算,还是多使用+-*/运算符,位运算符等.

‘肆’ 如何使用java实现加减乘除运算

publicclasstest{publicstaticvoidmain(String[]args){inta=5;intb=1;intc=a+b;intd=a-b;inte=a*b;intf=a/c;System.out.println(c,d,e,f);}}

‘伍’ Java的加减乘除问题

//JAVA编程:四则运算(接收用户输入的2个操作数,和运算符),计算之后,输出结果~~~~
import java.util.Scanner;
public class 四则运算 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入第一个数字:");
int a = sc.nextInt();
System.out.print("请输入运算符号:");
String str = sc.next();
char ch = str.charAt(0);
System.out.print("请输入第二个数字:");
int b = 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==0){
System.out.println("被除数为零,运算无意义!");
break;
}
else {
System.out.println(a+"/"+ b+ " = "+(a/b));
break;
}
default:
System.out.println("运算符是无意义字符!");
break;
}
}
}

望采纳~~~~~~~~

‘陆’ java的加减乘除运算

使用BigDecimal并且一定要用String来够造。
实现方法如下:

import java.math.BigDecimal;

/**

* 由于Java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精

* 确的浮点数运算,包括加减乘除和四舍五入。

*/

public class Arith{

//默认除法运算精度

private static final int DEF_DIV_SCALE = 10;

//这个类不能实例化

private Arith(){

}

/**

* 提供精确的加法运算。

* @param v1 被加数

* @param v2 加数

* @return 两个参数的和

*/

public static double add(double v1,double v2){

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.add(b2).doubleValue();

}

/**

* 提供精确的减法运算。

* @param v1 被减数

* @param v2 减数

* @return 两个参数的差

*/

public static double sub(double v1,double v2){

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.subtract(b2).doubleValue();

}

/**

* 提供精确的乘法运算。

* @param v1 被乘数

* @param v2 乘数

* @return 两个参数的积

*/

public static double mul(double v1,double v2){

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.multiply(b2).doubleValue();

}

/**

* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到

* 小数点以后10位,以后的数字四舍五入。

* @param v1 被除数

* @param v2 除数

* @return 两个参数的商

*/

public static double div(double v1,double v2){

return div(v1,v2,DEF_DIV_SCALE);

}

/**

* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指

* 定精度,以后的数字四舍五入。

* @param v1 被除数

* @param v2 除数

* @param scale 表示表示需要精确到小数点以后几位。

* @return 两个参数的商

*/

public static double div(double v1,double v2,int scale){

if(scale<0){

throw new IllegalArgumentException(

"The scale must be a positive integer or zero");

}

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();

}

/**

* 提供精确的小数位四舍五入处理。

* @param v 需要四舍五入的数字

* @param scale 小数点后保留几位

* @return 四舍五入后的结果

*/

public static double round(double v,int scale){

if(scale<0){

throw new IllegalArgumentException(

"The scale must be a positive integer or zero");

}

BigDecimal b = new BigDecimal(Double.toString(v));

BigDecimal one = new BigDecimal("1");

return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();

}

};

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

//参考下我刚写的这个,稍显得智能一些!你可以稍加更改;思路都注释的很详细了!
//代码也不算多,
importjava.util.Scanner;
publicclass计算器{
privatestaticScannersc=newScanner(System.in);
publicstaticvoidmain(String[]args){
init();
}
privatestaticvoidinit(){
while(true)
sop(input());
}
privatestaticStringinput(){
sop("请输入运算表达式如:1+1回车!");
Stringstr=sc.nextLine(),sum="";
chartem=0;
intpoin=0;
for(inti=0;i<str.length();i++){//遍历!
charcs=str.charAt(i);
if(cs=='+'||cs=='-'||cs=='*'||cs=='/'){//寻找找运算符号
tem=str.charAt(i);//记录运算符号!
poin=i;//记录符号位置!
break;
}elseif(i>=str.length()-1){
sop("输入不合法请检查!");
init();
}
}//拆分数字!
doublea=Double.parseDouble(str.substring(0,poin));
doubleb=Double.parseDouble(str.substring(poin+1));
switch(tem){//开始判断运算!
case'+':
sum=""+(a+b);
break;
case'-':
sum=""+(a-b);
break;
case'*':
sum=""+(a*b);
break;
default:
sum=""+(a/b);
break;
}
returnstr+"="+sum;
}//打印功能!
privatestaticvoidsop(Objectobj){
System.out.println(obj);
}
}

‘捌’ java加减乘除计算器界面编程

来源:Code Wizards HQ

智能观 编译

孩子想学编码的话,有很多方法可以展开学习。可以让他们学着构建视频游戏、创建动画、开发移动应用程序和搭建网站。不管孩子喜欢哪种形式,都有大量的编码书供他们快速学起来!

但是,怎么才能找到一本好的儿童编码书呢?


‘玖’ java如何实现3个 个位数的加减乘除运算

publicclassParamDemo{
publicstaticvoidmain(String[]args){
Map<String,Integer>map=newHashMap<>();
map.put("+",1);
map.put("-",1);
map.put("*",2);
map.put("/",2);

Scannerscanner=newScanner(System.in);
intnum1=scanner.nextInt();
intnum2=scanner.nextInt();
intnum3=scanner.nextInt();

Stringop1=scanner.next();
Stringop2=scanner.next();

//此时证明第一个操作符优先级大于第二个操作符
if(map.get(op1)-map.get(op2)>=0){
inttmpNumber=operateNum(op1,num1,num2);
System.out.println(operateNum(op2,tmpNumber,num3));
}else{
inttmpNumber=operateNum(op2,num2,num3);
System.out.println(operateNum(op1,num1,tmpNumber));
}

scanner.close();
}

privatestaticintoperateNum(Stringoperator,intnum1,intnum2){

switch(operator){
case"+":
returnnum1+num2;
case"-":
returnnum1-num2;
case"*":
returnnum1*num2;
case"/":
returnnum1/num2;
default:
return0;
}

}


}

‘拾’ 如何使用Java对象语言编写一个加减乘除计算器要有代码

下面文件名要为:JiSuanQi.java

importjava.awt.*;

importjava.awt.event.*;

publicclassJiSuanQi

{

Strings="",s1=null,s2=null;

Framef=newFrame("计算器");

TextFieldtf=newTextField(30);

Panelp1=newPanel();

Panelp2=newPanel();

Panelp3=newPanel();

Buttonbt1=newButton("=");

Buttonbt2=newButton("删除");

Button[]bt=newButton[16];

intid=0;

publicstaticvoidmain(String[]args)

{

newJiSuanQi().init();

}

publicvoidinit()

{

f.setBackground(newColor(85,247,253));

f.setLayout(newBorderLayout(4,4));

p2.setLayout(newGridLayout(4,4,4,4));

p3.setLayout(newBorderLayout(4,4));

f.setResizable(false);

f.add(p1,BorderLayout.NORTH);

f.add(p2);

p3.add(bt2,BorderLayout.NORTH);

p3.add(bt1);

p1.add(tf);

f.add(p3,BorderLayout.EAST);

String[]b={"1","2","3","+","4","5","6","-","7","8","9","*","0",".","复位","/"};

for(inti=0;i<16;i++)

{

bt[i]=newButton(b[i]);

p2.add(bt[i]);

}

bt[0].setForeground(Color.blue);

bt[1].setForeground(Color.blue);

bt[2].setForeground(Color.blue);

bt[4].setForeground(Color.blue);

bt[5].setForeground(Color.blue);

bt[6].setForeground(Color.blue);

bt[8].setForeground(Color.blue);

bt[9].setForeground(Color.blue);

bt[10].setForeground(Color.blue);

bt[12].setForeground(Color.blue);

bt[13].setForeground(Color.blue);

bt[3].setForeground(Color.red);

bt[7].setForeground(Color.red);

bt[11].setForeground(Color.red);

bt[15].setForeground(Color.red);

bt[14].setForeground(Color.red);

bt1.setForeground(Color.red);

bt2.setForeground(Color.red);

f.pack();

f.setVisible(true);

f.addWindowListener(newWindowAdapter()

{

publicvoidwindowClosing(WindowEvente)

{

System.exit(0);

}

}

);

bt[0].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=1;

s2+=1;

tf.setText(s);

}

}

);

bt[1].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=2;

s2+=2;

tf.setText(s);

}

}

);

bt[2].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=3;

s2+=3;

tf.setText(s);

}

}

);

bt[4].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=4;

s2+=4;

tf.setText(s);

}

}

);

bt[5].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=5;

s2+=5;

tf.setText(s);

}

}

);

bt[6].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=6;

s2+=6;

tf.setText(s);

}

}

);

bt[8].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=7;

s2+=7;

tf.setText(s);

}

}

);

bt[9].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=8;

s2+=8;

tf.setText(s);

}

}

);

bt[10].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=9;

s2+=9;

tf.setText(s);

}

}

);

bt[12].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=0;

s2+=0;

tf.setText(s);

}

}

);

bt[13].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+='.';

s2+='.';

tf.setText(s);

}

}

);

bt[3].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='+';

id=1;

s2="";

tf.setText(s);

}

}

);

bt[7].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='-';

id=2;

s2="";

tf.setText(s);

}

}

);

bt[11].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='*';

id=3;

s2="";

tf.setText(s);

}

}

);

bt[14].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s="";

s2="";

tf.setText(s);

}

}

);

bt[15].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='/';

id=4;

s2="";

tf.setText(s);

}

}

);

bt1.addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

if(id<1);

else{

s+='=';

doublea=Double.parseDouble(s1);

doubleb=Double.parseDouble(s2);

doublec=0;

switch(id)

{

case1:c=a+b;break;

case2:c=a-b;break;

case3:c=a*b;break;

case4:c=a/b;break;

}

s+=c;

tf.setText(s);

}

s="";s1="";s2="";id=0;

}

}

);

bt2.addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

char[]c1;

char[]c2=newchar[s.length()-1];

c1=s.toCharArray();

for(inti=0;i<s.length()-1;i++)

c2[i]=c1[i];

s=s.valueOf(c2);

if(id<1)

{

s1=s;

}

if(s2.length()>=1)

{

char[]c3;

char[]c4=newchar[s2.length()-1];

c3=s2.toCharArray();

for(inti=0;i<s2.length()-1;i++)

c4[i]=c3[i];

s2=s2.valueOf(c4);

}

tf.setText(s);

}

}

);

}

}

阅读全文

与java计算加减乘除相关的资料

热点内容
阿里云服务器终端在哪里 浏览:144
app纸有什么用 浏览:219
cuteftp命令 浏览:502
最开始的编程语言是什么 浏览:757
at远程命令 浏览:490
云服务器哪家好点 浏览:211
android系统源码阅读 浏览:924
dumpjava分析工具 浏览:678
怎么下载cpu源码 浏览:154
代码加密怎么取消 浏览:888
编译原理代码在哪里运行 浏览:584
解密摄影pdf 浏览:72
算法编程中级题目 浏览:250
c语言编译器毕业设计 浏览:717
医保卡申请app哪个好 浏览:945
阿里云服务器上传源码 浏览:602
营销管理科特勒pdf 浏览:696
愿望清单app哪个好 浏览:461
安卓外放声音怎么解决 浏览:195
脉脉app干什么用的 浏览:361