I wrote a program that performs certain operations (AND, OR, NOR, NAND, NOT, XOR) on two binary numbers and returns the result. I used a stringbuilder to produce the result. The program's method uses a for loop to look through each character in BinaryA (because they both have the same length) and then uses an algorithim based on a truth table to get the result.
The only issue i'm having is that the result keeps outputting either 00000000 or 11111111 as a result. I'm not sure what my logic issue is:
public class Driver {
public static void main(String[] args) {
String Operator = "AND";
String binA = "10110101";
String binB = "00110001";
System.out.println(Operator + " and binary numbers " + binA + " and " + binB + " result in the output " + doOperation(Operator, binA, binB));
}
public static StringBuilder doOperation(String Operator, String BinaryA, String BinaryB)
{
StringBuilder result = new StringBuilder();
for(int i = 0; i < BinaryA.length(); i++)
{
if(Operator.equals("AND"))
{
if(BinaryA.equals("1") && BinaryB.equals("1"))
result.append('1');
else
result.append('0');
}
else if (Operator.equals("OR"))
{
if(BinaryA.equals("0") && BinaryB.equals("0"))
result.append('0');
else
result.append('1');
}
else if (Operator.equals("NAND"))
{
if(BinaryA.equals("1") && (BinaryB.equals("1")))
result.append('0');
else
result.append('1');
}
else if (Operator.equals("NOR"))
{
if(BinaryA.equals("0") && (BinaryB.equals("0")))
result.append('1');
else
result.append('0');
}
else if (Operator.equals("XOR"))
{
if(BinaryA.equals("1") && BinaryB.equals("0") || (BinaryA.equals("0")) && BinaryB.equals("1"))
result.append('1');
else
result.append('0');
}
}
return result;
}
}
OUTPUT: AND and binary numbers 10110101 and 00110001 result in the output 00000000