Search code examples
javabooleantruthtable

How do I modify this truth table so that it uses and displays 1's and 0's rather than true and false


How do I modify this truth table so that it uses and displays 1's and 0's rather than true and false.

public class Table {
    public static void main(String args[]){

        boolean p,q;

        System.out.println("P\tQ\tAND\tOR\tXOR\tNOT");

        p = true;
        q = true;

        System.out.print(p+"\t"+q+"\t");
        System.out.print((p&q)+"\t"+(p|q)+"\t");
        System.out.println((p^q)+"\t"+(!p));

        p = true;
        q = false;

        System.out.print(p+"\t"+q+"\t");
        System.out.print((p&q)+"\t"+(p|q)+"\t");
        System.out.println((p^q)+"\t"+(!p));

        p = false;
        q = true;

        System.out.print(p+"\t"+q+"\t");
        System.out.print((p&q)+"\t"+(p|q)+"\t");
        System.out.println((p^q)+"\t"+(!p));

        p = false;
        q = false;

        System.out.print(p+"\t"+q+"\t");
        System.out.print((p&q)+"\t"+(p|q)+"\t");
        System.out.println((p^q)+"\t"+(!p));
    }
}

Solution

  • In Java, there exists no logical xor operator, only one for bitwise operations!

    See Oracle.com - Operators as reference


    Anyway, here your desired conversion from true and false Strings to 1 and 0:

    public static void main(String[] args) {
        System.out.println("P\tQ\tAND\tOR\tXOR\tNOT(p)");
    
        printTable(true, true);
        printTable(true, false);
        printTable(false, true);
        printTable(false, false);
    }
    
    private static void printTable(final boolean p, final boolean q) {
        System.out.printf("%s\t", p    ? "1" : "0");
        System.out.printf("%s\t", q    ? "1" : "0");
        System.out.printf("%s\t", p&&q ? "1" : "0");
        System.out.printf("%s\t", p||q ? "1" : "0");
        System.out.printf("%s\t", p^q  ? "1" : "0");
        System.out.printf("%s\t", !p   ? "1" : "0");
        System.out.printf("\n");
    }
    

    Output is

    P       Q       AND     OR      XOR     NOT (p)
    1       1       1       1       0       0   
    1       0       0       1       1       0   
    0       1       0       1       1       1   
    0       0       0       0       0       1