The output I get from this code is correct, but it isn't passing the task requirements (specifically the first two).
Why do I keep on having this issue?
Please help.
package en.codegym.task.pro.task09.task0908;
/*
Binary to hexadecimal converter
*/
public class Solution {
public static void main(String[] args) {
String binaryNumber = "100111010000";
System.out.println("Binary number " + binaryNumber + " is equal to hexadecimal number " + toHex(binaryNumber));
String hexNumber = "9d0";
System.out.println("Hexadecimal number " + hexNumber + " is equal to binary number " + toBinary(hexNumber));
}
public static String toHex(String binaryNumber) {
if (binaryNumber == null || binaryNumber.isEmpty()){
return "";
}
StringBuilder hexNumber = new StringBuilder();
for (int i = binaryNumber.length(); i >= 0; i -=4){
int endIndex = i;
int startIndex = Math.max(0, i - 4);
String binaryGroup = binaryNumber.substring(startIndex, endIndex);
hexNumber.insert(0, binarytoHex(binaryGroup));
}
return hexNumber.toString();
}
public static String toBinary(String hexNumber) {
if (hexNumber == null || hexNumber.isEmpty()){
return "";
}
StringBuilder binaryNumber = new StringBuilder();
for (int i = 0; i < hexNumber.length(); i++){
char hexDigit = hexNumber.charAt(i);
binaryNumber.append(hexToBinary(hexDigit));
}
return binaryNumber.toString();
}
// helper method to convert a 4-digit binary group to a hexadecimal digit
public static char binarytoHex(String binaryGroup){
if (binaryGroup.equals("0000")) return '0';
else if (binaryGroup.equals("0001")) return '1';
else if (binaryGroup.equals("0010")) return '2';
else if (binaryGroup.equals("0011")) return '3';
else if (binaryGroup.equals("0100")) return '4';
else if (binaryGroup.equals("0101")) return '5';
else if (binaryGroup.equals("0110")) return '6';
else if (binaryGroup.equals("0111")) return '7';
else if (binaryGroup.equals("1000")) return '8';
else if (binaryGroup.equals("1001")) return '9';
else if (binaryGroup.equals("1010")) return 'A';
else if (binaryGroup.equals("1011")) return 'B';
else if (binaryGroup.equals("1100")) return 'C';
else if (binaryGroup.equals("1101")) return 'D';
else if (binaryGroup.equals("1110")) return 'E';
else if (binaryGroup.equals("1111")) return 'F';
else return '0'; // Default to '0' if not a valid binary group
}
//helper method to convert a hexadecimal digit to 4-digit binary
public static String hexToBinary(char hexDigit){
switch (hexDigit) {
case '0':
return "0000";
case '1':
return "0001";
case '2':
return "0010";
case '3':
return "0011";
case '4':
return "0100";
case '5':
return "0101";
case '6':
return "0110";
case '7':
return "0111";
case '8':
return "1000";
case '9':
return "1001";
case 'A':
return "1010";
case 'B':
return "1011";
case 'C':
return "1100";
case 'D':
return "1101";
case 'E':
return "1110";
case 'F':
return "1111";
default:
return "0000"; // Default to '0000' if not a valid hexadecimal digit
}
}
}