Search code examples
javastackoperator-precedencepostfix-notation

Checking for Operators in Java


I was writing a code for infix to postfix conversion. However I'm unable to find a method to check for operators like (,),+,- etc. I could use ASCII but is there any method (like isLetter() etc) which I could use?Also how can i define the operator precedence?


Solution

  • . I could use ASCII but is there any method (like isLetter() etc) which I could use?

    Well I can suggest you Character.isDigit('1') or Character.isLetter('A') for checking whether this character is digit or letter but as customization I will go for ArrayList.

        ArrayList<Character> alist=new ArrayList<>();
        alist.add('+');
        alist.add('-');
        alist.add('/');
        alist.add('%');
        char c='A';
        if(alist.contains(c))
        {
            System.out.println("UNREACHABLE");
        }
    

    Secondly for operator precedence you can use

    HashMap<Character, Integer> hm=new HashMap<>();

    hmap.put('+',1);
    

    with key and value pair to determine it's precedence