当输入算式为字符串时,需要判断其计算优先级,本算法基于栈设计,可以处理括号,加减乘除以及次方运算。
算法如下
import java.util.HashMap;
import javatest.myStack;
public class zisushuru_jisuan {
public static HashMap<String,Integer> temp = new HashMap<String,Integer>();
public static void main(String[] args){
initpriority();
System.out.println("结果:"+calculate("(1+2)*4-(4-2)^3"));
}
static void initpriority(){
temp.put("(",0);
temp.put(")",4);
temp.put("+", 1);
temp.put("-", 1);
temp.put("*", 2);
temp.put("/", 2);
temp.put("^", 3);
}
public static char[] toArray(String input){
return input.toCharArray();
}
static String calculate(String input){
myStack in = new myStack();
myStack operand = new myStack();
myStack operator = new myStack();
char[] ch = toArray(input);
for(int i=ch.length-1;i>=0;i--){
in.push(String.valueOf(ch[i]));
}
if(in.isnum(in.peek())){
operand.push(in.getNext());
operator.push(in.getNext());
}else{
operator.push(in.getNext());
operand.push(in.getNext());
}
String temp1="";
while(!in.isEmpty()||!operator.isEmpty()){
if(in.isEmpty()){
while(!operator.isEmpty()){
String aa = result(operator.pop(),operand.pop(),operand.pop());
operand.push(aa);
}
return operand.pop();
}
temp1 = in.getNext();
if(in.isnum(temp1)){
operand.push(temp1);
}else if(operator.isEmpty()){
operator.push(temp1);
continue;
}else if(temp1.equals("(")){
operator.push("(");
}else if(temp1.equals(")")){
while(!operator.peek().equals("(")){
String aa = result(operator.pop(),operand.pop(),operand.pop());
operand.push(aa);
}
operator.pop();
continue;
}else if(temp.get(temp1)>temp.get(operator.peek())){
operator.push(temp1);
continue;
}else if(temp.get(temp1)<=temp.get(operator.peek())){
while(!operator.isEmpty()&&temp.get(temp1)<=temp.get(operator.peek())){
String aaa = result(operator.pop(),operand.pop(),operand.pop());
operand.push(aaa);
}
operator.push(temp1);
continue;
}
}
return operand.pop();
}
static String result(String operator,String b,String a){
switch(operator){
case "+": return Double.toString(Double.parseDouble(a)+Double.parseDouble(b));
case "-": return Double.toString(Double.parseDouble(a)-Double.parseDouble(b));
case "*": return Double.toString(Double.parseDouble(a)*Double.parseDouble(b));
case "/": return Double.toString(Double.parseDouble(a)/Double.parseDouble(b));
case "^": return Double.toString(Math.pow(Double.parseDouble(a),Double.parseDouble(b)));
}
return null;
}
}
此处为自定义的栈继承了Stack,添加了getNext方法,和isnum方法,getNext()方法用于从输入字符栈中取出一整个操作数或者操作符。比如若操作数是两位以上,则需要弹栈多次直至遇到操作符。
public class myStack extends Stack<String> {
String getNext(){
if(!this.isEmpty()){
String temp = "";
if(isnum(this.peek())){
while(!this.isEmpty()&&isnum(this.peek())){
temp+=this.pop();
}
return temp;
}
return this.pop();
}
return null;
}
boolean isnum(String a){
for(int j=0;j<a.length();j++){
if(!Character.isDigit(a.charAt(j))&&!(a.charAt(j)=='.')){
return false;
}
}
return true;
}
}
运行结果
