import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import
java.util.List;
/**
* 实现字符串输入之后的四则运算
* @author Administrator
*
*/
public class Math {
public static void
main(String[] args) throws IOException {
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
resultShow(br);
// System.out.println(9-7*8);
// System.out.println(getResult("9-7*8"));
}
public static void resultShow(BufferedReader br) throws
IOException{
System.out.print("请输入计算式:");
//开始接受用户指令
String str = br.readLine();
try {
double result = getResult(str);
if((double)0 == result -
(int)result){
System.out.println("计算后得出的结果为:"+(int)result);
}else{
System.out.println("计算后得出的结果为:"+result);
}
} catch (Exception e) {
// TODO Auto-generated catch
block
e.printStackTrace();
System.out.println("您输入的公式不正确!请重新输入");
resultShow(br);
}
}
/**
*
首先将计算式转换为Object数组,数字转为int,符号为String
* @param expr
*
@return
*/
public static double getResult(String expr){
//转换char数组
char[] cs = expr.toCharArray();
//转换后存放公式内容的容器
ListintData = new
ArrayList();
//这个对象用来存放一串连续数字的char字符
List temp = new ArrayList();
for (int i = 0; i = 0 && (i==cs.length-1 ||
((int)cs[i+1] - 48 temp){
String
s = "";
for (Iterator i = temp.iterator();
i.hasNext();) {
Character character = (Character) i.next();
s += character;
}
return
Double.parseDouble(s);
}
public static double
getActualResult(Object[] cs){
return kuohaoMath(cs);
}
/**
* 带括号计算,使用递归
*/
public static double
kuohaoMath(Object[] cs){
//找到扩号符的索引,正反括号
int[]
indexe敏感词indKuohaoIndex(cs);
if(indexes != null){
Object[] temp = new Object[indexes[1]-indexes[0]-1];
//截获括号里面的内容数组
for (int i = 0; i tempData = new ArrayList();
for (int i = 0; i =0; j--) {
if(cs[j].equals("(")){
indexes[0] = j;
break;
}
}
break;
}
}
return indexes;
}
/**
* 不包括括号运算的,普通运算算法
*/
public static double
normalMath(Object[] cs){
int index = -1;
//先乘法或除法,找到*,/的索引位置
index = findMultiplication(cs);
if(index >= 0){
List tempData = new
ArrayList();
//计算符号附近相邻值得结果
double result
= 0;
if(cs[index].equals("*")){
result =
(Double)cs[index-1] * (Double)cs[index+1];
}else{
result = (Double)cs[index-1] / (Double)cs[index+1];
}
//添加到新容器
for (int i = 0; i = 0){
List tempData = new
ArrayList();
//计算符号附近相邻值得结果
double result
= 0;
if(cs[index].equals("+")){
result =
(Double)cs[index-1] + (Double)cs[index+1];
}else{
result = (Double)cs[index-1] - (Double)cs[index+1];
}
for (int i = 0; i