In: Computer Science
Create a Java program which prints a truth table for any 2
variables propositional function.
Assuming variables p and q. Instead of the symbols for "and" and
"or", just used the words. For "not", use the tilde "~"
Prompt the user for 3 questions
1: "p and q"? Or "p or q"?
2: Do you want to negate p?
3: Do you want to negate q?
For example, suppose in a menu system the user chose "p or q", and to negate q. The output should look similar to this:
p | q | (p or ~q)
------------------
T | T | T
T | F | T
F | T | F
F | F | T
Explanation::
Code in JAVA::
import java.util.Scanner;
public class TruthTable {
public static void main(String[] args) {
/**
* We will use Scanner class object
named sc to take input from the user
* */
Scanner sc=new
Scanner(System.in);
/**
* In here we will ask user three
questions.
* */
int choice,negateP,negateQ;
System.out.print("\"p and q\"? or
\"p or q\"? Enter 1 for first option or 2 for second: ");
choice=sc.nextInt();
System.out.print("Do you want to
negate p? Enter 1 for yes or 2 for no : ");
negateP=sc.nextInt();
System.out.print("Do you want to
negate q? Enter 1 for yes or 2 for no : ");
negateQ=sc.nextInt();
System.out.print("\n p | q |
(");
if(negateP==2) {
System.out.print("p ");
}else {
System.out.print("~p ");
}
if(choice==1) {
System.out.print("and ");
}else {
System.out.print("or ");
}
if(negateQ==2) {
System.out.println("q)");
}else {
System.out.println("~q)");
}
System.out.println("-------------------------------");
System.out.print(" T | T |
");
System.out.println(value(choice,negateP,negateQ,true,true));
System.out.print(" T | F |
");
System.out.println(value(choice,negateP,negateQ,true,false));
System.out.print(" F | T |
");
System.out.println(value(choice,negateP,negateQ,false,true));
System.out.print(" F | F |
");
System.out.println(value(choice,negateP,negateQ,false,false));
}
public static char value(int choice,int negateP, int
negateQ,boolean a, boolean b) {
if(negateP==1) {
if(a) {
a=false;
}else {
a=true;
}
}
if(negateQ==1) {
if(b) {
b=false;
}else {
b=true;
}
}
if(choice==1) {
//and case
if(a==true
&& b==true) {
return 'T';
}else {
return 'F';
}
}else {
//or case
if(a==true ||
b==true) {
return 'T';
}else {
return 'F';
}
}
}
}
OUTPUT::
TEST CASE 1:
TEST CASE 2:
Please provide the feedback!!
Thank You!!