java写一个中缀表达式,要能够处理小数点和负数,输入-13+1,得到结果-12
时间: 2023-05-26 17:02:30 浏览: 47
以下是一个处理小数点和负数的中缀表达式的Java程序,该程序可以接受用户输入一个字符串形式的中缀表达式,然后通过栈来计算表达式的值:
import java.util.Stack;
import java.util.Scanner;
public class InfixExpression {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入中缀表达式:");
String expression = input.nextLine();
double result = calculate(expression);
System.out.println("结果是:" + result);
}
public static double calculate(String expression) {
Stack<Double> operandStack = new Stack<>();
Stack<Character> operatorStack = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (ch == ' ')
continue;
else if (ch == '(') {
operatorStack.push(ch);
} else if (ch == ')') {
while (operatorStack.peek() != '(')
operandStack.push(applyOperator(operatorStack.pop(), operandStack.pop(), operandStack.pop()));
operatorStack.pop();
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
while (!operatorStack.empty() && hasPrecedence(ch, operatorStack.peek()))
operandStack.push(applyOperator(operatorStack.pop(), operandStack.pop(), operandStack.pop()));
operatorStack.push(ch);
} else {
String operand = "";
while (i < expression.length() && (ch >= '0' && ch <= '9' || ch == '.' || ch == '-')) {
operand += ch;
i++;
if (i < expression.length())
ch = expression.charAt(i);
}
i--;
double value = Double.parseDouble(operand);
operandStack.push(value);
}
}
while (!operatorStack.empty())
operandStack.push(applyOperator(operatorStack.pop(), operandStack.pop(), operandStack.pop()));
return operandStack.pop();
}
public static double applyOperator(char operator, double operand2, double operand1) {
if (operator == '+')
return operand1 + operand2;
else if (operator == '-')
return operand1 - operand2;
else if (operator == '*')
return operand1 * operand2;
else if (operator == '/')
return operand1 / operand2;
else
return 0;
}
public static boolean hasPrecedence(char operator1, char operator2) {
if (operator2 == '(' || operator2 == ')')
return false;
if ((operator1 == '*' || operator1 == '/') && (operator2 == '+' || operator2 == '-'))
return false;
else
return true;
}
}
当用户输入-13 1时,上述程序会输出结果-12。