Java Reference
In-Depth Information
18
if
(count % NUMBER_OF_PRIMES_PER_LINE ==
0
) {
19
// Print the number and advance to the new line
20 System.out.printf(
"%-5s\n"
, number);
21 }
22
else
23 System.out.printf(
"%-5s"
, number);
24 }
25
26
// Check whether the next number is prime
27 number++;
28 }
29 }
30
31
/** Check whether number is prime */
32
public static boolean
isPrime(
int
number) {
isPrime
method
33
for
(
int
divisor =
2
; divisor <= number /
2
; divisor++) {
34
if
(number % divisor ==
0
) {
// If true, number is not prime
35
return false
;
// Number is not a prime
36 }
37 }
38
39
return true
;
// Number is prime
40 }
41 }
The first 50 prime numbers are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
We divided a large problem into two subproblems: determining whether a number is a prime
and printing the prime numbers. As a result, the new program is easier to read and easier to
debug. Moreover, the methods
printPrimeNumbers
and
isPrime
can be reused by other
programs.
This section presents a program that converts a hexadecimal number into a decimal
number.
Listing 5.11, Dec2Hex.java, gives a program that converts a decimal to a hexadecimal. How
would you convert a hex number into a decimal?
Given a hexadecimal number
h
n
h
n
-
1
h
n
-
2
c
h
2
h
1
h
0
, the equivalent decimal value is
h
n
Key
Point
16
n
16
n
-
1
16
n
-
2
*
+
h
n
-
1
*
+
h
n
-
2
*
+ c
16
2
16
1
16
0
+
h
2
*
+
h
1
*
+
h
0
*
For example, the hex number
AB8C
is
16
3
16
2
16
1
16
0
10
*
+
11
*
+
8
*
+
12
*
=
43916
Our program will prompt the user to enter a hex number as a string and convert it into a deci-
mal using the following method:
public static int
hexToDecimal(String hex)
Search WWH ::
Custom Search