answersLogoWhite

0


Best Answer

public class Exercise6{

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println("Example: " + addBinaryNumbers("100", "111")); // Result = 1011

// Test Cases :

// Valid Equivalence Class

// Since the inputs are valid, there will be no errors

assert (addBinaryNumbers("1", "1").equals("10") ) : "Valid Case 1: Error";

assert (addBinaryNumbers("10", "10").equals("100") ) : "Valid Case 2: Error";

assert (addBinaryNumbers("111", "111").equals("1110") ) : "Valid Case 3: Error";

assert (addBinaryNumbers("1110", "1011").equals("11001") ) : "Valid Case 4: Error";

// Invalid Equivalence Class

// Since the inputs are invalid, there will be errors

assert (addBinaryNumbers("2", "3").equals("101") ) : "Invalid Case 1: Error";

}

public static String addBinaryNumbers(String n1, String n2) {

String result = "";

for(int i = 0; i < n1.length(); i++) {

if ( (n1.charAt(i) != '0') && (n1.charAt(i) != '1') ) {

System.out.println("First number is invalid");

}

}

for(int i = 0; i < n2.length(); i++) {

if ( (n2.charAt(i) != '0') && (n2.charAt(i) != '1') ) {

System.out.println("Second number is invalid");

}

}

int number1 = Integer.parseInt(n1, 2);

int number2 = Integer.parseInt(n2, 2);

int resultNumber = number1 + number2;

result = Integer.toBinaryString(resultNumber);

return result;

}

}

User Avatar

Wiki User

βˆ™ 11y ago
This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: How do you add two binary numbers using java code?
Write your answer...
Submit
Still have questions?
magnify glass
imp