TheSaint321 TheSaint321 - 2 months ago 11
Java Question

Trying to convert Integer to HexDecimal without using methods or arrays in Java

So this is what I have so far but it prints out the hexadecimal backwards. How can I switch it to be forwards or is there an easier way to convert the integer to HexDecimal than I'm doing. This is a homework assignment and I'm not allowed to use arrays or predefined methods (I.E .toHexString()).

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int num = scn.nextInt();
int remainder;

while (num > 0) {

remainder = num % 16;
if (remainder == 10) {
System.out.print("a");
} else if (remainder == 11) {
System.out.print("b");
} else if (remainder == 12) {
System.out.print("c");
} else if (remainder == 13) {
System.out.print("d");
} else if (remainder == 14) {
System.out.print("e");
} else if (remainder == 15) {
System.out.print("f");
} else {
System.out.print(remainder);
}
num = num / 16;
}
}
}

Answer

If you want to go the non-recursive route, declare a String before you get into your loop and build onto it, rather than printing to System.out every loop iteration:

String output = "";
while (num > 0) {
  remainder = num % 16;
  if (remainder == 10) {
    output = "a" + output;
  } else if (remainder == 11) {
    output = "b" + output;
  } else if (remainder == 12) {
    output = "c" + output;
  } else if (remainder == 13) {
    output = "d" + output;
  } else if (remainder == 14) {
    output = "e" + output;
  } else if (remainder == 15) {
    output = "f" + output;
  } else {
    output = remainder + output;
  }
  num = num / 16;
}
System.out.println(output);