I was able to pass an integer number to hexadecimal. The problem now being tested was that the negative numbers do not work with this formula.
Here is the code I have:
public class PPROG_pl6_ex8 {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int num;
do {
num = askNum();
if (num == 0) {
System.exit(0);
} else {
System.out.println(convertToHex(num));
}
} while (num != 0);
}
private static int askNum() {
System.out.println("Introduza o número");
int num = input.nextInt();
return num;
}
public static String convertToHex(int num) {
int base = 16;
int alg;
String valueOfAlg;
String numero = "";
do {
alg = num % base;
num = num / base;
if (alg == 10) {
valueOfAlg = "A";
} else if (alg == 11) {
valueOfAlg = "B";
} else if (alg == 12) {
valueOfAlg = "C";
} else if (alg == 13) {
valueOfAlg = "D";
} else if (alg == 14) {
valueOfAlg = "E";
} else if (alg == 15) {
valueOfAlg = "F";
} else {
valueOfAlg = String.valueOf(alg);
}
/*
PARA TESTAR!
System.out.println("alg: " + alg);
System.out.println("num: " + num);
System.out.println("valueOfAlg: " + valueOfAlg);
System.out.println("numero: " + numero);
*/
numero = valueOfAlg + numero;
} while (num != 0);
return numero;
}
}
I also tried to put a condition for the negative numbers:
if(alg == -10)
valueOfAlg = "-A"
... and up to 15 below
But it also did not work because it had numbers like -f-f
.
I need help translating numbers into negatives.