Skip to content

Commit c60de3d

Browse files
author
jsquared21
committed
Add Ex 18.22
1 parent 37bc512 commit c60de3d

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Diff for: Exercise_18/Exercise_18_22/Exercise_18_22.class

1.27 KB
Binary file not shown.

Diff for: Exercise_18/Exercise_18_22/Exercise_18_22.java

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*********************************************************************************
2+
* (Decimal to hex) Write a recursive method that converts a decimal number into *
3+
* a hex number as a string. The method header is: *
4+
* *
5+
* public static String dec2Hex(int value) *
6+
* *
7+
* Write a test program that prompts the user to enter a decimal number and *
8+
* displays its hex equivalent. *
9+
*********************************************************************************/
10+
import java.util.Scanner;
11+
12+
public class Exercise_18_22 {
13+
/** Main method */
14+
public static void main(String[] args) {
15+
// Create a scanner
16+
Scanner input = new Scanner(System.in);
17+
18+
// Prompt the user to enter a decimal number
19+
System.out.print("Enter a decimal number: ");
20+
int value = input.nextInt();
21+
22+
// Display the value's hex equivalent
23+
System.out.println("The hex equivalent of "
24+
+ value + " is " + dec2Hex(value));
25+
}
26+
27+
/** Method converts a decimal number
28+
* into a hex number as string */
29+
public static String dec2Hex(int value) {
30+
String result = "";
31+
return dec2Hex(value, result);
32+
}
33+
34+
/** Recursive helper method */
35+
public static String dec2Hex(int value, String result) {
36+
int r = value % 16; // Remainder
37+
String remainder = r >= 10 ?
38+
String.valueOf((char)('A' + r % 10)) : String.valueOf(r);
39+
40+
if (value / 16 == 0) // Base case
41+
return remainder + result;
42+
else
43+
return dec2Hex(value / 16, remainder + result); // Recursive call
44+
}
45+
}

0 commit comments

Comments
 (0)