今天在学数据结构,自己撸一段用栈来实现后缀表达式求值的代码,能改进的地方还有很多,在此先mark一下
package StackPractice;
import java.util.Scanner;
import java.util.Stack;
import java.util.regex.Pattern;
public class PostfixCaculaterImpl {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入表达式,以空格进行分割。例:9 3 1 - 3 * + 10 2 / + ");
String str = sc.nextLine();// 空格分割,按行读取
count(str);
}
/*
* 用于判断字符时数字还是运算符
*/
public static boolean isNumeric(String string) {
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(string).matches();
}
/*
* 实现计算操作
*/
public static void count(String str) {
float op1 = 0;// 记录出栈数字
float op2 = 0;// 记录出栈数字
float result = 0;// 记录运算结果
Stack<String> stack = new Stack();// 创建栈对象
String[] arr = str.split(" ");// 对传入的字符串通过空格进行分割,并传入数组
for (int i = 0; i < arr.length; i++) {
// 对字符进行判断,如果为数字,则入栈;如果为运算符,则进行运算。
if (isNumeric(arr[i])) {
stack.push(arr[i]);
} else if (arr[i] == "+" || arr[i] == "-" || arr[i] == "*"
|| arr[i] == "/") {
op1 = Float.parseFloat((String) stack.pop());
op2 = Float.parseFloat((String) stack.pop());
// 根据运算符,选择合适的运算
switch (arr[i]) {
case "+":
result = add(op2, op1);
stack.push(result + "");
break;
case "-":
result = substaction(op2, op1);
stack.push(result + "");
break;
case "*":
result = multiply(op2, op1);
stack.push(result + "");
break;
case "/":
result = divide(op2, op1);
stack.push(result + "");
break;
default:
break;
}
} else {
System.out.println("输入有误,请重新输入!");
}
}
System.out.println("后缀表达式计算结果为:" + result);
}
public static float multiply(float a, float b) {
return a * b;
}
public static float divide(float a, float b) {
return a / b;
}
public static float add(float a, float b) {
return a + b;
}
public static float substaction(float a, float b) {
return a - b;
}
}