I need a program in java using 2 methods, named decimalToHex and toHexChar. The
ID: 3542270 • Letter: I
Question
I need a program in java using 2 methods, named decimalToHex and toHexChar. The first method decimalToHex will recieve an integer value from main method and build the hexadecimal string. It will utilize the second method toHexChar to convert an integer to a single hex digit in a character. Include notes/comments that explain each block of code!
Remember the Hexadecimal digits are 0 1 2 3 4 5 6 7 8 9 A B C D E F
Where a decimal 10=A, 11=B, 12=C, 13=D,14=E,15=F.
A Hexadecimal value of decimal 123 is 7B.
This problem will use modulus operator %. For example,
123 % 16 = 11 ---> B and 123/16=7
7 % 16 = 7----> 7 and 7/16=0 and we stop.
hence decimal 123 --->hexadecimal 7b
Sample Run/OUTPUT:
Enter a number (or -1 to exit): 123
The hexadecimal of 123 is 7B.
Enter a number (or -1 to exit): -1
Thank you!
The program will need to include 2 additional methods outside of the main()
method as below:
Method: Signature:
decimalToHex public static String decimalToHex(int decimal)
toHexChar public static char toHexChar(int hexValue)
Explanation / Answer
import java.util.*;
public class test
{
public static String decimalToHex(int decimal)
{
StringBuilder ans = new StringBuilder("");
while(decimal!=0)
{
ans.append(toHexChar(decimal%16));
decimal = decimal/16;
}
return ans.reverse().toString();
}
public static char toHexChar(int hexValue)
{
switch(hexValue)
{
case 1: return '1';
case 2: return '2';
case 3: return '3';
case 4: return '4';
case 5: return '5';
case 6: return '6';
case 7: return '7';
case 8: return '8';
case 9: return '9';
case 10: return 'A';
case 11: return 'B';
case 12: return 'C';
case 13: return 'D';
case 14: return 'E';
case 15: return 'F';
}
return ' ';
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int number = 0;
System.out.println("Enter a number (or -1 to exit): ");
number = in.nextInt();
while(number!=-1)
{
System.out.println("The hexadecimal of " + number + " is " + decimalToHex(number));
System.out.println("Enter a number (or -1 to exit): ");
number = in.nextInt();
}
System.out.println("Thank you!");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.