java - 为什么我的字符串变量没有被插入堆栈?

标签 java regex stack

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/

相关文章:

regex - 检查字符串是否包含孤立的单词

c - 程序在这里如何使用堆栈?

python - 与类(class)相关的问题

java - 在 MongoDB Java 驱动程序中使用数组字段的项目

java - 得到两个相同的陈述?

Java线程同步概念静态函数

java - 使用可变参数重载时方法不明确

javascript - String.match() for regex\s on chinese string 在 IE8 和 IE9/Chrome/Firefox/… 之间的工作方式不同

javascript - 如果没有匹配项,正则表达式返回 null

c - 使用 Visual Studio 2010 在 C 中返回失败类型