Search code examples
javabooleansemantics

Java, Insert a {} pair to make the code segment work as it should


The following code fragment is supposed to print "Type AB" when boolean variables typeA and typeB are both true, and print "Type O" when both variables are false. Instead, it prints "Type O" whenever just one of the variables is false.

I don't see the error in the code, what's wrong with it? I think it's useless as it doesn't print out whether one is Type A or Type B. Why not insert System.out.print("Type A") or System.out.print("Type B") after the first line?

if (typeA || type B)
    if (typeA && typeB)
        System.out.print("Type AB");
    else 
        System.out.print("Type O");

Solution

  • This would fix the conditions :

    if (typeA || type B) {
      if (typeA && typeB)
        System.out.print("Type AB");
    } else {
        System.out.print("Type O");
    }
    

    Without the curly braces, the else would be matched to the inner if, but you want to match it to the outer if.