0

I am trying to convert userinput's each characters to logical expression and trying to print the Boolean result. but I always get result as false.

Lets say user enters : (( (a|~B) & (C&D) ) & E & ( ~A | a | D&G )) my program convert this to an logical expression as written below and returns Boolean result.

(((false|false) & (true&true)) & true & (false | false|true&true))

But the result always shows false. When i write

System.out.println(true|true);

The output is True. But when my code returns the same expression it gives false.

Here is the code :

public class logicoperator {
boolean b;
static String  str;


    public boolean logicresult (String logexpression) {
    str = logexpression;
    str =   str.replaceAll("[ABCDEFG]", "t");
    str = str.replaceAll("[abcdefg]","f");
    str = str.replace("~t", "f");
    str = str.replace("~f", "t");
    String str1 = str.toString();

//System.out.println(str1);
    String op = "";
    char[] ch = str1.toCharArray();
        for(int i = 0; i< ch.length; i++) {
            if(ch[i] == 't') { op=op+"true";}
            else if(ch[i] == 'f') {op=op+"false";}
            else if(ch[i] == '(') {op=op+"(";}
            else if(ch[i] == '&') {op=op+"&";}
            else if(ch[i] == '|') {op=op+"|";}
            else if(ch[i] == ')') {op=op+")";}
            else if(ch[i] == '~') {op=op+"~";}


        }

        return (Boolean.valueOf(op));


        }
}
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
  • The fact that you're overwriting `str` *several* times is a smell... – Makoto Jul 30 '18 at 15:55
  • 3
    `Boolean.valueOf` does not do what you think it does. It simply translates literal "true" or "false" to their respective `boolean` values. It does not evaluate arbitrary expressions. – Joachim Sauer Jul 30 '18 at 15:58
  • 3
    Your assumption that `Boolean.valueOf()` parses and evaluates the string is wrong. *The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string "true".* – PM 77-1 Jul 30 '18 at 15:59
  • There was a similar question like an hour ago... – Coder-Man Jul 30 '18 at 16:00

0 Answers0