I am currently working through the work book, Java A Beginners Guide. Chapter 2 has a little project to create a truth table. The values that are displayed are in the format of true or false. The goal is to display 1's and 0's instead.
I have tried the below code to do this but the String.valueOf
method wont work for all of the expressions. I am out of idea's as to how i can do this.
package ChapterTwo;
public class LogicalOpTable {
public static void main(String[] args) {
boolean p, q;
System.out.println("P\tQ\tAND\tOR\tXOR\tNOT");
p = true; q = true;
String str0 = String.valueOf(p);
String str1 = String.valueOf(q);
str0 = true ? "1" : "2";
str1 = true ? "1" : "2";
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(str0 + "\t" + str1 +"\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));
}
}
Thanks all for the hints and tips, in the end my final code looks like the below. I know there are probably easier ways to do this but the book wants you to utilize all the stuff from the first two chapters, so i have included a control statement as well.
Please up vote if you think it is OK.
Thanks // Try this 2-2: a truth table for the logical operators. package ChapterTwo;
public class LogicalOpTable {
public static void main(String[] args) {
boolean p, q;
int a = 0, b = 0;
System.out.println("P\tQ\tAND\tOR\tXOR\tNOT");
p = true; q = true;
if(p) a = 1;
else a = 0;
if(q) b = 1;
else b = 0;
System.out.print(a + "\t" + b +"\t");
System.out.print(printBoolean(p&q) + "\t" + printBoolean (p|q) + "\t");
System.out.println(printBoolean2(p^q) + "\t" + printBoolean (!p));
p = true; q = false;
if(p) a = 1;
else a = 0;
if(q) b = 1;
else b = 0;
System.out.print(a + "\t" + b +"\t");
System.out.print(printBoolean(p&q) + "\t" + printBoolean (p|q) + "\t");
System.out.println(printBoolean2(p^q) + "\t" + printBoolean (!p));
p = false; q = true;
if(p) a = 1;
else a = 0;
if(q) b = 1;
else b = 0;
System.out.print(a + "\t" + b +"\t");
System.out.print(printBoolean(p&q) + "\t" + printBoolean (p|q) + "\t");
System.out.println(printBoolean2(p^q) + "\t" + printBoolean (!p));
p = false; q = false;
if(p) a = 1;
else a = 0;
if(q) b = 1;
else b = 0;
System.out.print(a + "\t" + b +"\t");
System.out.print(printBoolean(p&q) + "\t" + printBoolean (p|q) + "\t");
System.out.println(printBoolean2(p^q) + "\t" + printBoolean (!p));
}
public static String printBoolean(boolean p) {
return p ? "1" : "0";
}
public static String printBoolean2(boolean q) {
return q ? "1" : "0";
}
}