5
I was able to pass an integer number to hexadecimal. The problem now being tested is that the negative numbers do not work with this formula.
This 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 to the negative numbers:
if(alg == -10)
valueOfAlg = "-A"
... and forward up to 15
But I couldn’t because I had numbers like -f-f
.
I need help converting the numbers to negatives.
Related: https://answall.com/q/248453/64969
– Jefferson Quesado