0

I'm trying to figure out why this piece of code is not working, as the notation "156 154 152 - 3 + -" should go through without throwing an exception. Is there maybe a better way to use regex in this case? When I actually run my interpret function without manually throeing the exception, the result is correct and all is good. But for this exercise, there is a requirement for such exception handling.
Here's the code:


public class RegexTest {
    public static void main(String[] arg) {

        boolean b = check_notation("156 154 152 - 3 + -");
        System.out.println(b);
    }

    public static boolean check_notation(String pol){

        pol = pol.trim();
        String[] tokens = pol.split("\\s+");

        for (String r : tokens) {
            if (!(r.matches("-[0-9]*") || r.matches("[0-9]*") || r == "/" || r == "*" || r == "-" || r == "+")) {
                throw new RuntimeException("There are symbols that are not allowed.");
            }
        }

        return true;
    }
}

searchfind
  • 47
  • 1
  • 5
  • 1
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – WJS Oct 11 '20 at 15:58
  • 1
    I actually made the same mistake in another piece of code couple of days back. Old habits. Thanks a lot! It seems to work now. – searchfind Oct 11 '20 at 16:00
  • @searchfind - Was below answer worked for you? happy to help! – Zulfi Oct 12 '20 at 15:44

1 Answers1

1

@searchfind ... r.matches() was required for the special characters regex check. Also; \\ needs to be prefixed before + and * symbol regex to avoid dangling meta character exceptions.
Kindly use below Regex conditions

if (!(r.matches("-[0-9]*") || r.matches("[0-9]*") || r.matches("/") || 
                    r.matches("\\*") || r.matches("-") || r.matches("\\+"))) {
                throw new RuntimeException("There are symbols that are not allowed.");
            }
Zulfi
  • 61
  • 4