将运算符和操作数输入到两个不同的栈中
Input operators and operands into two different stacks
我想使用 Scanner 或任何更合适的方法从用户那里获取表达式作为输入,并将运算符压入一个堆栈,将操作数压入另一个堆栈。
所以如果我有类似的东西:52+3*(2-1)
我想用堆栈来评估它。
我想将整行作为字符串读取并将其更改为 char[],但问题是 52 将被读取为两个单独的字符。
您可以一次读取整行,然后使用 StringTokenizer 获取单个 operators/operands。
String example = "52+3*(2-1)";
String delim = "[/*-+()]";
StringTokenizer st = new StringTokenizer(example, delim, true);
while(st.hasMoreTokens())
{
// check if it's an operator or operand and add it to the appropriate stack
}
我想使用 Scanner 或任何更合适的方法从用户那里获取表达式作为输入,并将运算符压入一个堆栈,将操作数压入另一个堆栈。
所以如果我有类似的东西:52+3*(2-1)
我想用堆栈来评估它。
我想将整行作为字符串读取并将其更改为 char[],但问题是 52 将被读取为两个单独的字符。
您可以一次读取整行,然后使用 StringTokenizer 获取单个 operators/operands。
String example = "52+3*(2-1)";
String delim = "[/*-+()]";
StringTokenizer st = new StringTokenizer(example, delim, true);
while(st.hasMoreTokens())
{
// check if it's an operator or operand and add it to the appropriate stack
}