forked from ChrisMayfield/ThinkJava2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappe.tex
More file actions
357 lines (276 loc) · 10.9 KB
/
Copy pathappe.tex
File metadata and controls
357 lines (276 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
\chapter{Extras}
\label{extras}
This appendix contains previous sections of the book.
We chose to remove them from this edition, because they were not essential to meet the corresponding chapter's goals.
However, you may still find this material useful.
%%% Section 6.1 (second half)
\section{Unreachable code}
Sometimes it is convenient to write multiple \java{return} statements, for example, one in each branch of a conditional:
\begin{code}
public static double absoluteValue(double x) {
if (x < 0) {
return -x;
} else {
return x;
}
}
\end{code}
Since these \java{return} statements are in a conditional statement, only one will be executed.
As soon as either of them executes, the method terminates without executing any more statements.
\index{dead code}
\index{unreachable}
Code that appears after a \java{return} statement (in the same block), or any place else where it can never be executed, is called {\bf dead code}.
The compiler will give you an ``unreachable statement'' error if part of your code is dead.
For example, this method contains two lines of dead code:
\begin{code}
public static double absoluteValue(double x) {
if (x < 0) {
return -x;
System.out.println("This line is dead."); // error
} else {
return x;
}
System.out.println("So is this one."); // error
}
\end{code}
If you put \java{return} statements inside a conditional statement, you have to make sure that {\em every possible path} through the method reaches a \java{return} statement.
The compiler will let you know if that's not the case.
For example, the following method is incomplete:
\begin{code}
public static double absoluteValue(double x) {
if (x < 0) {
return -x;
} else if (x > 0) {
return x;
}
// error: missing return statement
}
\end{code}
When \java{x} is 0, neither condition is true, so the method ends without hitting a return statement.
The error message in this case might be something like ``missing return statement'', which is confusing since there are already two.
Compiler errors like ``unreachable statement'' and ``missing return statement'' often indicate a problem with your algorithm, not the code.
In the previous example, \java{if (x > 0)} is unnecessary because \java{x} will always be positive or zero at that point.
Changing that \java{else if} to an \java{else} resolves the error.
\begin{description}
\term{dead code}
Part of a program that can never be executed, often because it appears after a \java{return} statement.
\end{description}
%%% Section 6.5
\section{Boolean methods}
\index{boolean}
\index{method!boolean}
Methods can return \java{boolean} values, just like any other type, which is often convenient for hiding tests inside methods.
For example:
\begin{code}
public static boolean isSingleDigit(int x) {
if (x > -10 && x < 10) {
return true;
} else {
return false;
}
}
\end{code}
The name of this method is \java{isSingleDigit}.
It is common to give \java{boolean} methods names that sound like yes/no questions.
Since the return type is \java{boolean}, the return statement has to provide a boolean expression.
The code itself is straightforward, although it is longer than it needs to be.
Remember that the expression \java{x > -10 && x < 10} has type \java{boolean}, so there is nothing wrong with returning it directly (without the \java{if} statement):
\begin{code}
public static boolean isSingleDigit(int x) {
return x > -10 && x < 10;
}
\end{code}
In \java{main}, you can invoke the method in the usual ways:
\begin{code}
System.out.println(isSingleDigit(2));
boolean bigFlag = !isSingleDigit(17);
\end{code}
The first line displays {\tt true} because 2 is a single-digit number.
The second line sets \java{bigFlag} to \java{true}, because 17 is {\em not} a single-digit number.
Conditional statements often invoke \java{boolean} methods and use the result as the condition:
\begin{code}
if (isSingleDigit(z)) {
System.out.println("z is small");
} else {
System.out.println("z is big");
}
\end{code}
Examples like this one almost read like English:
``If is single digit z, print ... else print ...''.
%%% Section 7.2
\section{Generating tables}
\index{table}
\index{logarithm}
%Loops are good for generating and displaying tabular data.
Before computers were readily available, people had to calculate logarithms, sines and cosines, and other common mathematical functions by hand.
To make that easier, there were books of tables where you could look up values of various functions.
Creating these tables by hand was slow and boring, and the results were often full of errors.
When computers appeared on the scene, one of the initial reactions was: ``This is great!
We can use a computer to generate the tables, so there will be no errors.''
That turned out to be true (mostly), but shortsighted.
Not much later, computers were so pervasive that printed tables became obsolete.
\index{division!floating-point}
Even so, for some operations, computers use tables of values to get an approximate answer, and then perform computations to improve the approximation.
In some cases, there have been errors in the underlying tables, most famously in the table the original Intel Pentium used to perform floating-point division (see \url{https://en.wikipedia.org/wiki/Pentium_FDIV_bug}).
Although a ``log table'' is not as useful as it once was, it still makes a good example of iteration.
The following loop displays a table with a sequence of values in the left column and their logarithms in the right column:
\begin{code}
int i = 1;
while (i < 10) {
double x = i;
System.out.println(x + " " + Math.log(x));
i = i + 1;
}
\end{code}
The output of this program is:
\begin{stdout}
1.0 0.0
2.0 0.6931471805599453
3.0 1.0986122886681098
4.0 1.3862943611198906
5.0 1.6094379124341003
6.0 1.791759469228055
7.0 1.9459101490553132
8.0 2.0794415416798357
9.0 2.1972245773362196
\end{stdout}
\java{Math.log} computes natural logarithms, that is, logarithms base $e$.
For computer science applications, we often want logarithms with respect to base 2.
To compute them, we can apply this equation:
%
\[ \log_2 x = \frac{log_e x}{log_e 2} \]
%
We can modify the loop as follows:
\begin{code}
int i = 1;
while (i < 10) {
double x = i;
System.out.println(x + " " + Math.log(x) / Math.log(2));
i = i + 1;
}
\end{code}
And here are the results:
\begin{stdout}
1.0 0.0
2.0 1.0
3.0 1.5849625007211563
4.0 2.0
5.0 2.321928094887362
6.0 2.584962500721156
7.0 2.807354922057604
8.0 3.0
9.0 3.1699250014423126
\end{stdout}
Each time through the loop, we add one to \java{x}, so the result is an arithmetic sequence.
If we multiply \java{x} by something instead, we get a geometric sequence:
\begin{code}
final double LOG2 = Math.log(2);
int i = 1;
while (i < 100) {
double x = i;
System.out.println(x + " " + Math.log(x) / LOG2);
i = i * 2;
}
\end{code}
\index{final}
The first line stores \java{Math.log(2)} in a \java{final} variable to avoid computing that value over and over again.
The last line multiplies \java{x} by 2.
The result is:
\begin{stdout}
1.0 0.0
2.0 1.0
4.0 2.0
8.0 3.0
16.0 4.0
32.0 5.0
64.0 6.0
\end{stdout}
This table shows the powers of two and their logarithms, base 2.
Log tables may not be useful anymore, but for computer scientists, knowing the powers of two helps a lot!
%When you have an idle moment, you should memorize the powers of two up to 65536 (that's $2^{16}$).
%%% Section 7.6
\section{The do-while loop}
\index{pretest loop}
The \java{while} and \java{for} statements are {\bf pretest loops}; that is, they test the condition first and at the beginning of each pass through the loop.
\index{posttest loop}
\index{do-while}
Java also provides a {\bf posttest loop}: the \java{do}-\java{while} statement.
This type of loop is useful when you need to run the body of the loop at least once.
%NOTE: can we find an example that's better using do-while than using while-break?
For example, in Section~\ref{validate} we used the \java{return} statement to avoid reading invalid input from the user.
We can use a \java{do}-\java{while} loop to keep reading input until it's valid:
\begin{code}
Scanner in = new Scanner(System.in);
boolean okay;
do {
System.out.print("Enter a number: ");
if (in.hasNextDouble()) {
okay = true;
} else {
okay = false;
String word = in.next();
System.err.println(word + " is not a number");
}
} while (!okay);
double x = in.nextDouble();
\end{code}
Although this code looks complicated, it is essentially only three steps:
\begin{enumerate}
\item Display a prompt.
\item Check the input; if invalid, display an error and start over.
\item Read the input.
\end{enumerate}
\index{System.err}
The code uses a flag variable, \java{okay}, to indicate whether we need to repeat the loop body.
If \java{hasNextDouble()} returns \java{false}, we consume the invalid input by calling \java{next()}.
We then display an error message via \java{System.err}.
The loop terminates when \java{hasNextDouble()} return \java{true}.
\begin{description}
\term{pretest loop}
A loop that tests the condition before each iteration.
\term{posttest loop}
A loop that tests the condition after each iteration.
\end{description}
%%% Section 7.7
\section{Break and continue}
Sometimes neither a pretest nor a posttest loop will provide exactly what you need.
In the previous example, the ``test'' needed to happen in the middle of the loop.
As a result, we used a flag variable and a nested \java{if}-\java{else} statement.
\index{break}
A simpler way to solve this problem is to use a \java{break} statement.
When a program reaches a \java{break} statement, it exits the current loop.
\begin{code}
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
if (in.hasNextDouble()) {
break;
}
String word = in.next();
System.err.println(word + " is not a number");
}
double x = in.nextDouble();
\end{code}
Using \java{true} as a conditional in a \java{while} loop is an idiom that means ``loop forever'', or in this case ``loop until you get to a \java{break} statement.''
\index{continue}
In addition to the \java{break} statement, which exits the loop, Java provides a \java{continue} statement that moves on to the next iteration.
For example, the following code reads integers from the keyboard and computes a running total.
The \java{continue} statement causes the program to skip over any negative values.
\begin{code}
Scanner in = new Scanner(System.in);
int x = -1;
int sum = 0;
while (x != 0) {
x = in.nextInt();
if (x <= 0) {
continue;
}
System.out.println("Adding " + x);
sum += x;
}
\end{code}
Although \java{break} and \java{continue} statements give you more control of the loop execution, they can make code difficult to understand.
Use them sparingly.
%TODO explain other uses of \java{break}
%\section{The switch statement}
%%% was going to be in Ch07