62,616
社区成员
发帖
与我相关
我的任务
分享
package test;
public class Test1 {
private String[] a = { "+", "-", "*", "/", "(", ")" };
public int outcome(String str) {
int i = 0;
int j = 0;
int sum = 0;
int m = 0;
if ((i = str.indexOf(a[4])) >= 0) {//去除括号
if(str.substring(i+1,str.substring(i+1).indexOf(a[5])).indexOf(a[4])>=0){
i=i+str.substring(i+1,str.substring(i+1).indexOf(a[5])).lastIndexOf(a[4])+1;
}
j=i+str.substring(i+1).indexOf(a[5])+1;
m = outcome(str.substring(i + 1, j));
m = outcome(str.substring(0, i) + m + str.substring(j + 1));
} else if ((i = str.indexOf(a[2])) > 0 | (j = str.indexOf(a[3])) > 0) {//乘除计算
int[] c = {};
if ((i > 0 && j <= 0) || (i > 0 && j > 0 && i < j)) {
c = b(str, i);
} else {
c = b(str, j);
}
sum = account(str, c);
m = outcome(str.substring(0, c[0]) + sum + str.substring(c[2]));
} else if ((i = str.indexOf(a[0])) > 0 | (j = str.indexOf(a[1])) > 0) {//加减计算
int[] c = {};
if ((i > 0 && j <= 0) || (i > 0 && j > 0 && i < j)) {
c = b(str, i);
} else {
c = b(str, j);
}
sum = account(str, c);
m = outcome(str.substring(0, c[0]) + sum + str.substring(c[2]));
} else {//没有符号时直接转换
m = Integer.parseInt(str);
}
return m;
}
/**
* 主要是计算指定计算符号左右的数开始和结尾
* @param str 是要计算的字符串
* @param i 计算符号的位置
* @return int[]数组是第一个是数字开始 第二个是计算符号的位置 第三个是数字结束
*/
public int[] b(String str, int i) {
int j = 0;
int n = str.length();
for (int k = 0; k < 4; k++) {
if (str.substring(0, i).lastIndexOf(a[k]) > j) {
j = str.substring(0, i).lastIndexOf(a[k]) + 1;
}
if (str.substring(i + 1).indexOf(a[k]) > 0
&& str.substring(i + 1).indexOf(a[k]) < n) {
n = str.substring(i + 1).indexOf(a[k]) + i + 1;
}
}
return new int[] { j, i, n };
}
/**
* 计算指定计算符号左右数的结果 即"6*7" 返回 42
* @param str
* @param b
* @return 计算结果
*/
public int account(String str, int[] b) {
int sum = 0;
int f1 = Integer.parseInt(str.substring(b[0], b[1]));
int f2 = Integer.parseInt(str.substring(b[1] + 1, b[2]));
if (str.charAt(b[1]) == '+') {
sum = f1 + f2;
} else if (str.charAt(b[1]) == '-') {
sum = f1 - f2;
} else if (str.charAt(b[1]) == '*') {
sum = f1 * f2;
} else if (str.charAt(b[1]) == '/') {
sum = f1 / f2;
}
return sum;
}
public static void main(String[] args) {
Test1 t = new Test1();
System.out.println(t.outcome("((5*5)+(1+(10*8+16)/(4*6)))"));
}
}