Java Reference
In-Depth Information
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 = remainder+result ;
} else {
result = ( char )( 'A' +remainder 10)+resul t ;
number/=16;
System. out . println ( "The number in hexadecimal is: " +result ) ;
}
}
Examine the code: result = remainder+result . This means that the value of the
character remainder will be added at the beginning of the string.
3.6 Summary
The chapter introduced the three loop types in Java: while , do-while ,and for .The
two while loops are used when we want to keep repeating the same list of operations until
some event happens. For example, we may want to read input from the keyboard until a
positive number is entered. The difference between the two while loops is that the do-while
loop guarantees that the body of the loop will be executed at least once. Conversely, if the
condition inside a while statement is initially false, then the body of the while loop will
never be executed.
The for loop is perfect when counting is involved. For example, one can use a for loop
to print the numbers from 1 to 10. A for loop usually has one or more counter variables
that change after every execution of the body of the loop. When the middle condition of
the for loop becomes false, the body of the loop stops repeating and the program continues
from the line that is immediately after the for loop.
The chapter also introduces the modulus (a.k.a., remainder) operator. It is used to
calculate the remainder of dividing two integers.
3.7 Syntax
￿ i++;
Increment i by one.
￿ i--;
Decrement i by one.
Make a equal to i andthenincrement i by one.
￿
a = i++;
 
Search WWH ::




Custom Search