Andrej Tomas Andrej Tomas - 3 months ago 15
Java Question

What do I have to do, so the program would output 1 and 0 instead of true and false?

While practicing Java, I came up with a

Truth Table
program for logical operators.
Now, I can't figure out how to display 1 and 0 instead of true and false.

Here is my code:

public class Main {

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));
}

}

Answer

Instead of below lines:

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

You can do as below

print(p,q);
print(p&q, p|q);
print(p^q, !p);

private void print(boolean left, boolean right)
{
    System.out.println((left?1:0) + "\t" + (right?1:0))
}
Comments