I've been working on the number system calculator (refer to my binary question) and now i'm stuck at the Hexadecimal part. I've been using switch structure but the output goes like this:
Enter Number: 165
Enter Base: 16
The answer: A105
actual answer should be A5 tho, the remainder 10 which is A is showing up.
and here's my code:
int given = 0, base = 0, remainder = 0;
String output = "";
if (base == 2||base == 8){
while(given != 0){
remainder = given % base;
given /= base;
output = remainder + output;
}
System.out.println(output);
}
else if (base == 16){
while (given > 0){
remainder = given % base;
if (remainder <= 10){
System.out.print("");
}
switch(remainder){
case 10:System.out.print("A");break;
case 11:System.out.print("B");break;
case 12:System.out.print("C");break;
case 13:System.out.print("D");break;
case 14:System.out.print("E");break;
case 15:System.out.print("F");break;
}
given /= base;
output = remainder + output;
}
System.out.println(output);
}
Should I choose to continue the switch structure or is there something wrong with my code?
Edit: To make it clear, output
variable will reverse the value of the specific given. If I have a 37 as a decimal converted to binary, it would output 101001 which the actual answer is 100101.
You are printing A to F letters, and in addition adding the remainder to the output. You should add the letter to the output instead of printing them:
while (given > 0){
remainder = given % base;
if (remainder >= 10){
switch(remainder){
case 10:output = "A" + output;break;
case 11:output = "B" + output;break;
case 12:output = "C" + output;break;
case 13:output = "D" + output;break;
case 14:output = "E" + output;break;
case 15:output = "F" + output;break;
}
} else {
output = remainder + output;
}
given /= base;
}
System.out.println(output);