package test;
/*
计算数学表达式的值
*/
public class Cal {
public int cal(String str){
int result=0;
int value1,value2;
str = str.trim();
str = str.replaceAll(" ","");
while(true){
int index1 = str.indexOf("*");
int index2 = str.indexOf("/");
if(index1 == -1 && index2 == -1)
break;
int index=0;
if(index1>index2 && index2 != -1){
index = index2;
}
if(index2 == -1){
index = index1;
}
if(index1 == -1){
index = index2;
}
if(index2>index1 && index1 != -1){
index = index1;
}
{
String sub1=null;
String sub2=null;
value1 = 0;
for(int j=index-1;j>=0;j--){
char c = str.charAt(j);
if(c>='0' && c<='9'){
if(j==0){
sub1 = str.substring(j,index);
value1 = Integer.parseInt(sub1);
}
continue;
}
else{
sub1 = str.substring(j+1,index);
value1 = Integer.parseInt(sub1);
break;
}
}
value2 = 0 ;
for(int j=index+1;j<str.length();j++){
char c = str.charAt(j);
if(c>='0' && c<='9'){
if(j==str.length()-1){
sub2 = str.substring(index+1); // 修改为index+1
value2 = Integer.parseInt(sub2);
}
continue;
}
else{
sub2 = str.substring(index+1,j);
value2 = Integer.parseInt(sub2);
break;
}
}
int temp = (index1>index2 && index2!=-1) || index1==-1?value1/value2:value1*value2;
str = (index1>index2 && index2!=-1) || index1==-1?
str.replace(sub1+"/"+sub2,String.valueOf(temp)):str.replace(sub1+"*"+sub2,String.valueOf(temp));
}
}
// + -
while(true){
int index1 = str.indexOf("+");
int index2 = str.indexOf("-");
if(index1 == -1 && (index2 == -1 || index2 == 0)) //解决开头是"-"的问题
break;
int index=0;
if(index1>index2 && index2 != -1){
index = index2;
}
if(index2 == -1 || index2 == 0){ //解决开头是"-"的问题
index = index1;
}
if(index1 == -1){
index = index2;
}
if(index2>index1 && index1 != -1){
index = index1;
}
{ //查找操作数
String sub1=null;
String sub2=null;
value1 = 0;
for(int j=index-1;j>=0;j--){
char c = str.charAt(j);
if(c>='0' && c<='9'){
if(j==0){
sub1 = str.substring(j,index);
value1 = Integer.parseInt(sub1);
}
continue;
}
else{
if(j==0)
sub1 = str.substring(j,index);
else
sub1 = str.substring(j+1,index); //解决开头是"-"的问题
value1 = Integer.parseInt(sub1);
break;
}
}
value2 = 0 ;
for(int j=index+1;j<str.length();j++){
char c = str.charAt(j);
if(c>='0' && c<='9'){
if(j==str.length()-1){
sub2 = str.substring(index+1); // 修改为index+1
value2 = Integer.parseInt(sub2);
}
continue;
}
else{
sub2 = str.substring(index+1,j);
value2 = Integer.parseInt(sub2);
break;
}
}
// 为了解决开头是“-”的问题,下面的两行中的index2!=-1 修改为index2>0
int temp = (index1>index2 && index2>0) || index1==-1?value1-value2:value1+value2;
str = (index1>index2 && index2>0) || index1==-1?
str.replace(sub1+"-"+sub2,String.valueOf(temp)):str.replace(sub1+"+"+sub2,String.valueOf(temp));
}
}
result = Integer.parseInt(str);
return result;
}
public static void main(String[] args){
String str = "3-4*5+3";
Cal cal = new Cal();
System.out.println(cal.cal(str));
}
}