0

Beginner to Java here, I'm trying to convert infix expressions to postfix expressions but I'm having trouble understanding how to check if the token created by StringTokenizer is a number. I tried the tokens.equals() method but realized it wouldn't be effective since the numbers won't always be 1 digit numbers.

public String infixToPostfix() {

    Stack<String> s = new Stack<>();

    String expression = jtfInfix.getText();
    String delims = "+-*/() ";

    StringTokenizer strToken = new StringTokenizer(expression, delims, true); 

    String postFix = "";

    while (strToken.hasMoreTokens()) {
        String token = strToken.nextToken();
        // if the next token is a number, append it to the result
        if (token!=delims) {
            postFix += token;
        }
    }

}
Jake Miller
  • 2,432
  • 2
  • 24
  • 39
lio
  • 75
  • 2
  • 8
  • Take a look over [here](https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – aliaksei Apr 08 '18 at 21:41

1 Answers1

1

Checking that a String is a number can be tricky because there are so many cases. I wouldn't suggest writing code on your own unless you plan on accepting simple values, such as positive whole numbers (of any digital length). To do this simple check, you can use Regular Expressions:

token.matches("\\d+");

That will match one or more numbers (digits).

For more complex matching (such as decimal values and negative numbers), see How to check if a String is numeric in Java.


Example usage:

"1".matches("\\d+");      // true
"1057".matches("\\d+");   // true
"".matches("\\d+");       // false
"1.0".matches("\\d+");    // false
"-1".matches("\\d+");     // false
Justin Albano
  • 3,809
  • 2
  • 24
  • 51