简体   繁体   中英

Java: The logic of the conditional statement doesn't work and allows the program to run even when the conditions are not met

I have the following two lines of code, where I have set certain conditions for a conditional statement to execute. However, there is something wrong with the logic, because the program inside the conditional runs even when the conditions are not met.

if (!(token.equals('+')) && !(token.equals('-')) && !(token.equals('*')) && !(token.equals('/'))) {
            operandStack.push(Integer.valueOf(token));
        }

I am getting a java.lang.NumberFormatException: For input string: "whatever operator (+,-,* and /) that I enter in my test case" in the second line of this code and I realize that it's because Integer.valueOf() doesn't work for symbols, but that's the thing. If it's a symbol, it shouldn't be executing in the first place. I have tried looking for all kinds of typos or stupid syntax mistakes, but haven't found any. What's wrong with this logic?

You might do better to check if the token is an integer via a regular expression:

if (token.matches("\\d+")) {
    operandStack.push(Integer.parseInt(token));
}

And then parse the string into an integer.

The pattern \\d+ (double escaped for Java) matches on one or more digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM