您的位置:首页 > 其它

输入一个表达式,没有括号,数字小于0-9之间,输出计算结果,所有的中间结果化为整形。 例如: 输入:3+8×2/9-2 输出:2

2015-03-28 01:56 633 查看
输入一个表达式,没有括号,数字小于0-9之间,输出计算结果,所有的中间结果化为整形。

例如: 输入:3+8×2/9-2

输出:2

菜鸟初试,还请大神指教。

import java.util.Stack;

public class Calequ {

public int getRet(String str){

char[] arr = str.toCharArray();

Stack<Character> stack1 = new Stack<Character>();
//存储数字

Stack<Character> stack2 = new Stack<Character>();
//存储+-符号

int temp = 0,temp1,temp2;

char tempstr;

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

switch(arr[i]){

case '×':

temp1 = (int)(stack1.pop())-48;
//ASCII转换

temp = temp1*((int)(arr[i+1])-48);

stack1.push((char)(temp+48));

i++;

break;

case '/':

temp1 = (int)(stack1.pop())-48;

temp = temp1/((int)(arr[i+1])-48);

stack1.push((char)(temp+48));

i++;

break;

case '+':

if(stack2.size()!=0){

temp2 = (int)(stack1.pop())-48;

temp1 = (int)(stack1.pop())-48;

tempstr = stack2.pop();

if(tempstr=='+'){

temp = temp1+temp2;

}else{

temp = temp1-temp2;

}

stack1.push((char)(temp+48));

}

stack2.push(arr[i]);

break;

case '-':

if(stack2.size()!=0){

temp2 = (int)(stack1.pop())-48;

temp1 = (int)(stack1.pop())-48;

tempstr = stack2.pop();

if(tempstr=='+'){

temp = temp1+temp2;

}else{

temp = temp1-temp2;

}

stack1.push((char)(temp+48));

}

stack2.push(arr[i]);

break;

default:

stack1.push(arr[i]);

}

}

tempstr = stack2.pop();

temp2 = (int)(stack1.pop())-48;

temp1 = (int)(stack1.pop())-48;

if(tempstr=='+'){

temp = temp1+temp2;

}else{

temp = temp1-temp2;

}

return temp;

}

public static void main(String[] args){

String str = "3+8×2/9-2";

Calequ cal = new Calequ();

int result = cal.getRet(str);

System.out.println(result);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐