Aufgabe : Schreiben Sie eine Methode toHex, die für einen ganzzahligen Eingabewert (int) die hexadezimale Repräsentation als String berechnet. Entwickeln Sie Ihre Methode gemäß des gegebenen Dokumentationskommentars.
Frage: Was ist an meinem Code falsch/wieso funktioniert es nicht?
Mein Code:
public class Hex{
/**
* Berechnet die hexadezimale Darstellung der Zahl und gibt diese als String zurück
*
* @param input Die Zahl (int), die umgerechnet werden soll
* @Return die hexadezimale Darstellung als String
*/
private static String toHex(int input) {
String hex = "";
int i = 0;
if (input == 0) {
return hex;
} else {
if ((input % 16) == 1) {
hex = "1";
} else if ((input % 16) == 2) {
hex = "2";
} else if ((input % 16) == 3) {
hex = "3";
} else if ((input % 16) == 4) {
hex = "4";
} else if ((input % 16) == 5) {
hex = "5";
} else if ((input % 16) == 6) {
hex = "6";
} else if ((input % 16) == 7) {
hex = "7";
} else if ((input % 16) == 8) {
hex = "8";
} else if ((input % 16) == 9) {
hex = "9";
} else if ((input % 16) == 10) {
hex = "10";
} else if ((input % 16) == 11) {
hex = "B";
} else if ((input % 16) == 12) {
hex = "C";
} else if ((input % 16) == 13) {
hex = "D";
} else if ((input % 16) == 14) {
hex = "E";
} else if ((input % 16) == 15) {
hex = "F";
} else {
i = (input % 16);
hex += i;
}
return toHex(input / 16) + hex;
}
}
}
Frage: Was ist an meinem Code falsch/wieso funktioniert es nicht?
Mein Code:
public class Hex{
/**
* Berechnet die hexadezimale Darstellung der Zahl und gibt diese als String zurück
*
* @param input Die Zahl (int), die umgerechnet werden soll
* @Return die hexadezimale Darstellung als String
*/
private static String toHex(int input) {
String hex = "";
int i = 0;
if (input == 0) {
return hex;
} else {
if ((input % 16) == 1) {
hex = "1";
} else if ((input % 16) == 2) {
hex = "2";
} else if ((input % 16) == 3) {
hex = "3";
} else if ((input % 16) == 4) {
hex = "4";
} else if ((input % 16) == 5) {
hex = "5";
} else if ((input % 16) == 6) {
hex = "6";
} else if ((input % 16) == 7) {
hex = "7";
} else if ((input % 16) == 8) {
hex = "8";
} else if ((input % 16) == 9) {
hex = "9";
} else if ((input % 16) == 10) {
hex = "10";
} else if ((input % 16) == 11) {
hex = "B";
} else if ((input % 16) == 12) {
hex = "C";
} else if ((input % 16) == 13) {
hex = "D";
} else if ((input % 16) == 14) {
hex = "E";
} else if ((input % 16) == 15) {
hex = "F";
} else {
i = (input % 16);
hex += i;
}
return toHex(input / 16) + hex;
}
}
}