gpt4 book ai didi

java - 在 Java 中解决简单的字符串表达式 (1+2*3) [几乎完成]

转载 作者:行者123 更新时间:2023-12-04 00:33:43 30 4
gpt4 key购买 nike

我正在尝试解决简单的字符串表达式,例如1+2*3/4,无括号。我已经完成了简单的整数部分,上面的表达式可以完美地工作,但现在我被十进制值困住了,例如 1.1/2.2*4.4 我想要的只是将整个十进制数压入堆栈( double ),我我已经为此工作了一段时间,但还没有完全理解,非常感谢您的帮助。当前代码是:

import java.util.Stack;
import java.text.DecimalFormat;

public class EvaluateString
{
public static double evaluate(String expression)
{
char[] tokens = expression.toCharArray();
DecimalFormat df = new DecimalFormat("#.##");

// Stack for numbers: 'values'
Stack<Double> values = new Stack<Double>();

// Stack for Operators: 'ops'
Stack<Character> ops = new Stack<Character>();

for (int i = 0; i < tokens.length; i++)
{
// Current token is a whitespace, skip it
if (tokens[i] == ' ')
continue;

// Current token is a number, push it to stack for numbers
if (tokens[i] >= '0' && tokens[i] <= '9')
{
StringBuffer sbuf = new StringBuffer();
// There may be more than one digits in number
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
sbuf.append(tokens[i++]);
values.push(Double.parseDouble(sbuf.toString()));
}

// Current token is an operator.
else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/')
{
// While top of 'ops' has same or greater precedence to current
// token, which is an operator. Apply operator on top of 'ops'
// to top two elements in values stack
while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
values.push(applyOp(ops.pop(), values.pop(), values.pop()));

// Push current token to 'ops'.
ops.push(tokens[i]);
}
}

// Entire expression has been parsed at this point, apply remaining
// ops to remaining values
while (!ops.empty())
values.push(applyOp(ops.pop(), values.pop(), values.pop()));

// Top of 'values' contains result, return it
return Double.parseDouble(df.format(Double.parseDouble(String.valueOf(values.pop()))));
}

// Returns true if 'op2' has higher or same precedence as 'op1',
// otherwise returns false.
public static boolean hasPrecedence(char op1, char op2)
{
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}

// A utility method to apply an operator 'op' on operands 'a'
// and 'b'. Return the result.
public static double applyOp(char op, double b, double a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
}

将值推送到“值”堆栈的部分将发生一些变化。

最佳答案

为什么要自己编码?有许多第三方替代方案:

关于java - 在 Java 中解决简单的字符串表达式 (1+2*3) [几乎完成],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21484152/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com