Steven R
Steven R

Reputation: 323

Creating a binary truth "table"

First time posting on here! So ive searched and searched and cant find an answer. I dont really need a table, just to have that kind of output such as 0 and 0 = 0, 0 and 1 = 1, and so on... I need to read from a file that will extract the numbers and they are 0 0..0 1..1 0..1 1 I need to then make the AND, OR, NAND, and NOR "table" for them. I created an arrayList for them, so i can access them easier. the method i was going to do doesnt work and will take very long lines of code and pretty much be duplicated stuff. Im trying to think of a way to use a loop, but have mental block. can anyone help me please? heres what im talking about the code i have

    int rec3a = Integer.parseInt(list1.get(2));
    int rec3b = Integer.parseInt(list1.get(3));
        System.out.println("AND:");
        if(rec3a == 0 && rec3b == 0)
        {
            System.out.println("0");
        }
        if(rec3a == 0 && rec3b == 1)
        {
            System.out.println("0");
        }
        if(rec3a == 1 && rec3b == 0)
        {
            System.out.println("0");
        }
        if(rec3a == 1 && rec3b == 1)
        {
            System.out.println("1");
        }
    }

this doesnt really work for the OR statement either..its just a giant mess lol..any help would be appreciated

Upvotes: 0

Views: 460

Answers (3)

Elliott Frisch
Elliott Frisch

Reputation: 201447

You could use the bitwise operators,

int rec3a = 1;
int rec3b = 0;
// AND
System.out.println(rec3a & rec3b);
// OR
System.out.println(rec3a | rec3b);
// NAND
System.out.println((rec3a & rec3b) == 1 ? 0 : 1);
// NOR
System.out.println((rec3a | rec3b) == 1 ? 0 : 1);

Which (in this example) outputs

0
1
1
0

Upvotes: 3

Sinkingpoint
Sinkingpoint

Reputation: 7634

With Integers 0 and 1, you can use the built in bit-wise operators:

System.out.println(rec3a & rec3b); //AND
System.out.println(rec3A | rec3b); //OR

Upvotes: 2

Paul R
Paul R

Reputation: 212979

You could simplify this to:

    if (rec3a == 1 && rec3b == 1)
    {
        System.out.println("1");
    }
    else
    {
        System.out.println("0");
    }

For the OR case it would be:

    if (rec3a == 1 || rec3b == 1)
    {
        System.out.println("1");
    }
    else
    {
        System.out.println("0");
    }

Upvotes: 2

Related Questions