Java Reference
In-Depth Information
the remainder is bigger than 9, then the corresponding letter will be saved. After the loop,
the string will be printed in reverse order. Here is the implementation of the program.
import java . util . ;
public class Test {
public static void main(String [] args) {
System. out . println ( "Please enter a decimal number: " );
Scanner keyboard = new Scanner(System. in) ;
int number = keyboard . nextInt () ;
String result = "" ;
while (number > 0) {
int remainder = number % 16;
if (remainder < =9) {
result = result + remainder;
} else {
result = result + ( char )( 'A' +remainder 10) ;
number/=16;
System. out . print ( "The number in hexadecimal is: " );
for ( int i=0; i
{
System. out . print ( result . charAt( result . length ()
<
result . length() ; i++)
i
1)) ;
System. out . println () ;
}
}
The program first reads the number from the keyboard. Then there is a while loop. In
the loop the number is divided by 16 and the remainder is concatenated to the variable
result . This continues until the number becomes 0. Note that the line: number/=16 divides
the number by 16. As explained in Chapter 1, this algorithm will give us the number in
hexadecimal representation, but the digits will be reversed.
Note that when the remainder is bigger than 9, it needs to be converted to a character.
For example, if the remainder is 12, then 12
10 will be equal to 2. Looking at Figure 2.8,
we can see that the ASCII code of
A
is 65. When we add 2 to 65 we will get the number 67.
'
'
The ASCII code of 67 is
will be concatenated to the variable result .
In general, Java treats characters and integers similarly. For example, if we try to add a
character to an integer, then the result will be an integer. The character will be converted
to an integer using the ASCII table and then the addition will be performed. Conversely,
the ASCII table is also used when an integer is cast to a character. Adding a number to the
character
C
and therefore
C
'
'
'
'
is a common trick. For example, (char)('A'+23) will give us the 24 nd letter
of the English language (i.e., the letter
A
'
'
).
The code after the while loop displays the String variable result in reverse order. The
length method returns the length of the string. The charAt method gives us the character
at the specified position. Note that the first character of the string is at location 0. This is
why the last character of the string is at location result.length()-1 .When i is equal to
0, the character at position result.length()-1 will be displayed. When i is equal to 1,
the second to last character will be displayed and so on.
Note that we did not really have to create the string in reverse order. Alternatively, we
could have added every new digit of the string to the beginning of the string and eliminated
the code that reversed the string. Here is the rewrite.
import java . util . ;
X
'
'

Search WWH ::

Custom Search