Java Reference
In-Depth Information
try {
readTextFile();
} catch (IOException ioe) {
// deal with IO errors
} finally {
closeTextFile();
}
Today's first project shows how a finally statement can be used inside a method.
The HexReader application in Listing 7.1 reads sequences of two-digit hexadecimal num-
bers and displays their decimal values. There are three sequences to read:
n
000A110D1D260219
n
78700F1318141E0C
n
6A197D45B0FFFFFF
As you learned on Day 2, “The ABCs of Programming,” hexadecimal is a base-16 num-
bering system where the single-digit numbers range from 00 (decimal 0) to 0F (decimal
15), and double-digit numbers range from 10 (decimal 16) to FF (decimal 255).
LISTING 7.1
The Full Text of HexReader.java
1: class HexReader {
2: String[] input = { “000A110D1D260219 “,
3: “78700F1318141E0C “,
4: “6A197D45B0FFFFFF “ };
5:
6: public static void main(String[] arguments) {
7: HexReader hex = new HexReader();
8: for (int i = 0; i < hex.input.length; i++)
9: hex.readLine(hex.input[i]);
10: }
11:
12: void readLine(String code) {
13: try {
14: for (int j = 0; j + 1 < code.length(); j += 2) {
15: String sub = code.substring(j, j+2);
16: int num = Integer.parseInt(sub, 16);
17: if (num == 255)
18: return;
19: System.out.print(num + “ “);
20: }
21: } finally {
22: System.out.println(“**”);
23: }
7
Search WWH ::




Custom Search