The following code should convert a decimal to hexadecimal in Java: System.out.p
ID: 3561442 • Letter: T
Question
The following code should convert a decimal to hexadecimal in Java:
System.out.println("The decimal number you enter will be converted to its hexadecimal equivalent.");
System.out.println("Please enter a decimal number: ");
Scanner keyboard = new Scanner(System.in);
int dec = keyboard.nextInt();
int input = dec;
String hex = "";
char dig[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
while(dec > 0)
{
input = dec%16;
hex = dig[input] + hex;
dec = dec / 16;
}
System.out.println("The decimal number you entered, " + input + " is " + hex + " in hexadecimal. ");
}
The conversion works fine, where you see input in System.out.println("The decimal number you entered, " + input + " is " + hex + " in hexadecimal. "); shows the wrong value and I think it is because it is modified during the coding process. Any idea how to fix this? Thanks.
Explanation / Answer
Try this
import java.io.*;
class Dec2Hex
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter a decimal number : ");
int n=Integer.parseInt(br.readLine());
int r;
String s=""; //variable for storing the result
//array storing the digits (as characters) in a hexadecimal number system
char dig[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(n>0)
{
r=n%16; //finding remainder by dividing the number by 16
s=dig[r]+s; //adding the remainder to the result
n=n/16;
}
System.out.println("Output = "+s);
}
}
THis code is working fine on my pc..
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.