待解决问题
解决任意整数或小数的加减乘除四则运算。
解决方法
在后缀表达式中把整数或小数放到圆括号里,将它们作为一个整体来处理,例如,"2+50"会转换为"2(50)+","2.1+1.2"会被转换为"(2.1)(1.2)+"。
程序只需在读到的元素为数字时,继续读取下一个元素,下一个元素为数字或小数点则将它与之前的数字拼接到一起,最后当遇到操作符时,把拼接的数字串放到圆括号中,压入栈中。
代码实现
- 符号优先级的初始化
private static Map<String,Integer> priorityMap = new HashMap<String,Integer>();
private static String symPattern = "";
private Stack<String> stack = new Stack<String>();
static{
symPattern = "[+\\-*/]";
priorityMap.put("+", -1);
priorityMap.put("-", -1);
priorityMap.put("*", 1);
priorityMap.put("/", 1);
}
- 标准表达式输入
public String input(){
Scanner scanner = new Scanner(System.in);
String str = "";
if(scanner.hasNext()){
str += scanner.next();
}
System.out.println("the value of str = " + str);
return str;
}
- 校验输入的表达式是否合法
public boolean checkInput(String input) throws Exception{
char[] array = input.toCharArray();
for(int i=0;i<array.length;i++){
if(i<array.length - 1){
String prev = String.valueOf(array[i]);
String next = String.valueOf(array[i+1]);
//减号需要转义!
if(!prev.matches("[\\d\\.+\\-*/]")||!next.matches("[\\d\\.+\\-*/]")){
throw new Exception("输入中含有非法字符,请重新输入!");
}else if(prev.matches("[\\.+\\-*/]")&&next.matches("[\\.+\\-*/]")){
throw new Exception("输入了连续的符号!请重新输入!");
}else if(prev.matches("/")&&next.matches("0")){
throw new Exception("分母不能为零!");
}
}
}
return true;
}
- 将中缀表达式转为后缀表达式
public String generateSuffixExp(String input){
char[] array = input.toCharArray();
String suffix = "";
for(int i = 0;i < array.length;i++){
String atom = String.valueOf(array[i]);
if(atom.matches(symPattern)){
if(stack.isEmpty()){
stack.push(atom);
}else{
while(!stack.isEmpty()&&priorityMap.get(stack.peek()) >= priorityMap.get(atom)){
suffix += stack.pop();
}
stack.push(atom);
}
}else{
//如果取得的字符是数字的话,则将数字或小数点拼接到一起,如(2.1),继续遍历
while((i+1 < array.length)&&!(String.valueOf(array[i+1])).matches(symPattern)){
atom += array[++i];
}
if(atom.length() != 1){
atom = "(" + atom +")";
}
suffix +=atom;
}
}
while(!stack.isEmpty()){
suffix += stack.pop();
}
return suffix;
}
- 计算后缀表达式
public String resuleCompute(String suffix){
String result = "";
for(int i=0;i<suffix.length();i++){
String atom = String.valueOf(suffix.charAt(i));
if(atom.matches("\\d")){
stack.push(atom);
}else if(atom.matches("\\(")){
atom = "";
while(!String.valueOf(suffix.charAt(++i)).equals(")")){
atom += String.valueOf(suffix.charAt(i));
}
stack.push(atom);
}else{
float a = Float.parseFloat(stack.pop());
float b = Float.parseFloat(stack.pop());
float resultExp = this.getMiddleResult(a, b, atom);
stack.push(""+resultExp);
}
}
//在stack中,弹出结果,可以处理只输入数值的情况,比如输入2.1
result = stack.pop();
stack.clear();
return result;
}
public float getMiddleResult(float a,float b,String symbol){
if("+".equals(symbol)){
return b + a;
}else if("-".equals(symbol)){
return b - a;
}else if("*".equals(symbol)){
return b * a;
}else{
return b / a;
}
}
- 执行程序
public static void main(String[] args) throws Exception{
Cal_Version_2 cal = new Cal_Version_2();
while(true){
String input = cal.input();
if(cal.checkInput(input)){
String suffix = cal.generateSuffixExp(input);
System.out.println("the value of suffix is " + suffix);
System.out.println(cal.resuleCompute(suffix));
}
}
}
- 执行结果
50.2+20.5
the value of str = 50.2+20.5
the value of suffix is (50.2)(20.5)+
70.7
结果讨论
我们可以输入的任意的整数或小数进行运算,但是程序还有很大的局限性,比如如何去解决2*(3+4)这种优先级控制的情况。括号的引入会增加程序的复杂性,当然解决思路是大同小异的。