Search code examples
javamultiple-columnstruthtable

Truth table fun, Java


My program is currently printing out a preprogrammed truth table followed by the correct char at the end of each line. I would like to go above and beyond this program but I've run into a wall, I have never linked the output of a column to a function call in a for loop, and I can't seem to find anything close to it online. Essentially what I want to do is if 0 comes up in the p column I would assign p char 'F', and if a 1 comes up I would assign p char 'T'. My planned code is as follows:

public static void main(String args[])
{
    char p = 'T';
    char q = 'F';
    char r = 'T';
    int rows = (int) Math.pow(2,3);

    for (int i=0; i<rows; i++) {
        for (int j=3-1; j>=0; j--) {
            System.out.print((i/(int) Math.pow(2, j))%2 + " ");

        }
        System.out.println(LProp(p,q,r));
    }

}

Here is my LProp function:

private static char LProp(char p, char q, char r)
{
    // Logical expression
    //(~q /\r /\~p) \/(~(r \/~p))

    return return ORlogic(ANDlogic(NOTlogic(q),ANDlogic(r,NOTlogic(p))), NOTlogic(ORlogic(r,NOTlogic(p))));
}

Is it worth it, or even possible to assign the columns 1 and 0s to my chars? The output, by the way, is a 4 column table with 8 rows outputting the char T or F in the 4th column.

p q r LProp(p,q,r)
0 0 0 F
0 0 1 T

etc.


Solution

  • You can write a simple helper method to get the correct char value for a given boolean value:

    public static char getCharForBoolean(boolean value)
    {
        if (value) {
            return 'T';
        } else {
            return 'F';
        }
    }
    

    You can optimize this method by writing something like return value ? 'T' : 'F'; if you understand the ? operator.

    Use this method in your code where you want the character instead of the boolean value.

    bool result = LProp(p, q, r); // assuming it does return a boolean value
    System.out.println(getCharForBoolean(result));