Everyone I was wondering if there's a simple way of converting the true and false values of this Java program, into 1's and 0's without doing too much manual labour?. I figured adding the data type "byte" and having two separate variable values of 1 and 0 and manually inputting them into the code would do but, is there a simpler way?
public class LogicalOpTable1 {
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));
}
}
You have much code duplication. Never copy paste, Always create methods. This will make your code readable and maintainable. Even in a simple exercise like this it is always good practice.
The easiest way to print
1
or0
is to use the ternary operator,boolean ? 1 : 0
will do the trick in very few characters.Now, splitting your code into methods and applying the ternary operator we have:
A little bit better you'll agree?
Output:
You can then make the whole lot a little less hard-coded by making the
tabDelimited
method print any number ofboolean
s: