我希望我创建的这段代码可以帮助您了解,这是一个使用二进制(0 和 1)数字而不是布尔值(TRUE,FALSE)显示真值表的简单代码
/**
* Truth table for the logical operators. Using
* zeros and ones.
*
* @ Samuel Mayol
*/
public class LogicalOpTable {
public static void main(String[] args) {
boolean p, q;
byte p1, q1, pAndQ, pOrQ, pXORq, notP, pq;
System.out.println("Using 0s and 1s for the Truth Table:");
System.out.println("P\tQ\tAND\tOR\tXOR\tNOT"); // using tabs \t
pq =1;
switch (pq) { // without break it will execute the whole swich case statements
case 1 :
p = true; q = true;
p1=(byte) (p?1:0); // The ? : operator in Java
q1=(byte) (q?1:0); // Short form for Java If statement
pAndQ=(byte) ((p&q)?1:0);
pOrQ=(byte) ((p|q)?1:0);
pXORq=(byte) ((p^q)?1:0);
notP= (byte) ((!p)?1:0);
System.out.print(p1 + "\t" + q1 + "\t");
System.out.print(pAndQ + "\t" + pOrQ + "\t");
System.out.println(pXORq + "\t" + notP);
case 2:
p = true; q = false;
p1=(byte) (p?1:0); // The ? : operator in Java
q1=(byte) (q?1:0); // Short form for Java If statement
pAndQ=(byte) ((p&q)?1:0);
pOrQ=(byte) ((p|q)?1:0);
pXORq=(byte) ((p^q)?1:0);
notP= (byte) ((!p)?1:0);
System.out.print(p1 + "\t" + q1 + "\t");
System.out.print(pAndQ + "\t" + pOrQ + "\t");
System.out.println(pXORq + "\t" + notP);
case 3:
p = false; q = true;
p1=(byte) (p?1:0); // The ? : operator in Java
q1=(byte) (q?1:0); // Short form for Java If statement
pAndQ=(byte) ((p&q)?1:0);
pOrQ=(byte) ((p|q)?1:0);
pXORq=(byte) ((p^q)?1:0);
notP= (byte) ((!p)?1:0);
System.out.print(p1 + "\t" + q1 + "\t");
System.out.print(pAndQ + "\t" + pOrQ + "\t");
System.out.println(pXORq + "\t" + notP);
case 4:
p = false; q = false;
p1=(byte) (p?1:0); // The ? : operator in Java
q1=(byte) (q?1:0); // Short form for Java If statement
pAndQ=(byte) ((p&q)?1:0);
pOrQ=(byte) ((p|q)?1:0);
pXORq=(byte) ((p^q)?1:0);
notP= (byte) ((!p)?1:0);
System.out.print(p1 + "\t" + q1 + "\t");
System.out.print(pAndQ + "\t" + pOrQ + "\t");
System.out.println(pXORq + "\t" + notP);
}
}
}
运行此代码后的结果是:
Using 0s and 1s for the Truth Table:
P Q AND OR XOR NOT
1 1 1 1 0 0
1 0 0 1 1 0
0 1 0 1 1 1
0 0 0 0 0 1