Write a program to convert from decimal to Hexadecimal. CANNOT use Integer.toHex
ID: 3550610 • Letter: W
Question
Write a program to convert from decimal to Hexadecimal. CANNOT use Integer.toHexString(in). Program also has to check if decimal entered is possitive.This is what I have so far. Cannot figure out what I am doing wrong. When I enter 25 result comes out as 1 which is not wright.
import java.lang.*;
import java.util.Scanner;
public class FindHexString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String hex = "";
int decimal = 0;
int remainder = 0;
int quotient = 0;
System.out.print("Enter a number to be converted: ");
decimal = input.nextInt();
while (decimal > 16) {
quotient = decimal / 16;
remainder = decimal % 16;
do {
remainder = decimal % 16;
if (remainder == 10) {
hex = "A" + hex;
}
if (remainder == 11) {
hex = "B" + hex;
}
if (remainder == 12) {
hex = "C" + hex;
}
if (remainder == 13) {
hex = "D" + hex;
}
if (remainder == 14) {
hex = "E" + hex;
} else if (remainder == 15) {
hex = "F" + hex;
}
} while (decimal < 16);
decimal--;
}
System.out.print("Your number in hexadecimal is: " + hex + quotient);
}
}
Explanation / Answer
Please Rate My answer.
import java.lang.*;
import java.util.Scanner;
public class FindHexString
{
long int num;
long int rem[50],i=0,length=0;
System.out.print("Enter the decimal number : ");
num= input.nextInt();
while(num>0)
{
rem[i]=num%16;
num=num/16;
i++;
length++;
}
for(i=length-1;i>=0;i--)
{
switch(rem[i])
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("C");
break;
case 13:
printf("D");
break;
case 14:
printf("E");
break;
case 15:
printf("F");
break;
default :
system.out.print("%ld",rem[i]);
}
}
System.out.print("Your number in hexadecimal is: " + hex + quotient);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.