import java.util.*;
public class Pemdas {
public static double Express(String str)
{
Stack<Double> num = new Stack<Double>();
Stack<String> op = new Stack<String>();
String number = "[0-9]*"; // any digit from 0-9
for (int i = 0; i < str.length(); i++)
{
if (str.substring(i,i+1).equals(number))
num.push(Double.parseDouble(str.substring(i, i+1)));
else if (str.substring(i, i+1).equals("+"))
op.push(str.substring(i, i +1));
System.out.println(str);
}
double n = num.pop();
if (op.pop().equals("+"))
n = n + num.pop();
return n;
}
public static void main(String[] args)
{
System.out.print("Enter an Expression: ");
String ex = StdIn.readString(); // This is where I enter my string input
System.out.println(Express(ex));
}
}
假设我有一个字符串变量“5 + 5”作为我的输入。在 for 循环中,5 应该被插入 num 堆栈,但我不断收到 ESE,我不明白为什么。
最佳答案
当您想要与正则表达式匹配时,您可以使用equals()
。 equals()
用于比较文字字符串。您可能想要matches()
:
if (str.substring(i,i+1).matches(number))
num.push(Double.parseDouble(str.substring(i, i+1)));
<小时/>
事实上,这里根本不需要正则表达式。您可以通过执行以下操作来简化循环:
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (Character.isDigit(c))
num.push((double) (c - '0'));
else if (c == '+')
op.push("+");
System.out.println(str);
}
<小时/>
最后,请遵循 Java 的命名约定并调用您的方法 express()
而不是 Express()
。
关于java - 为什么我的字符串变量没有被插入堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18709630/