Kendel Ventonda Kendel Ventonda - 1 month ago 10
Java Question

Convertig Int to Hexdecimal with two digits without using imports in Java

I have a task to write a programm that converts an Int that can range from 0 to 255, into a hexdecimal that has two "digits". We got the recommendation to do this via modulo and switch-case.
While I'm not really sure if I understand how the convertion would look like in theory, I tried it like this:

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int set = 0;
do {
System.out.println("Bitte eine positive Zahl von 0 bis 255 eingeben");
while (!sc.hasNextInt()) {
System.out.println("Das ist keine Zahl!");
sc.next();
}
set = sc.nextInt();
} while (set > 255 || set < 0);
System.out.println("Danke, wir arbeiten mit " + set);

String Hex ="";
int Dez2;
int Dez = set;

do {
Dez2 = 16%Dez;
System.out.println(Dez2);

switch(Dez2){
case 0:
Hex = "A";
break;
case 1:
Hex = "B";
break;
case 2:
Hex = "C";
break;
case 3:
Hex = "D";
break;
case 4:
Hex = "E";
break;
case 5:
Hex = "F";
break;
default:
System.out.println("nothing");
}
Hex = Dez+Hex;
Dez=Dez/16;
}while (Dez<1);

System.out.println("Hex lautet " + Hex);
}


It shows a couple issues, which bases on the fact, that I have no clue how the conversation would work. I hope someone can help me here.

Answer

Here are some hints:

  • Consider a string of hex letters: String hexletters = "0123456789ABCDEF";
  • The first hex digit of num is num / 16: a number between 0 and 15 (inclusive)
  • The second hex digit of num is num % 16: a number between 0 and 15 (inclusive)
  • Strings have an .charAt(index) function that returns the character at the specified index.

You should be able to piece together the solution from these elements.