Kendel Ventonda Kendel Ventonda - 3 months ago 26
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(;
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!");;
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;

case 0:
Hex = "A";
case 1:
Hex = "B";
case 2:
Hex = "C";
case 3:
Hex = "D";
case 4:
Hex = "E";
case 5:
Hex = "F";
Hex = Dez+Hex;
}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.


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.