forked from sergutsan/groovyck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercises_d4.tex
396 lines (336 loc) · 12.2 KB
/
exercises_d4.tex
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
\documentclass{article}
\usepackage[margin=2cm]{geometry}
\begin{document}
\section*{Learning goals}
\label{sec:learning-goals}
Before the next day, you should have achieved the following learning
goals:
\begin{itemize}
\item Be able to create new methods, with or without parameters.
\item Be able to create new methods, free or inside classes.
\item Be able to use methods to avoid repeating code.
\item Understand the scope of a variable in a piece of code.
\item Understand how memory changes (both stack and heap) when a
method is called and executed, in particular when several methods
call each other.
\end{itemize}
Remember that star exercises are more difficult.
\textbf{Do not try star-exercises unless the other ones are clear to
you}.
\section{Scope}
\label{sec:scope}
Look at the following code (with line numbers for clarity) and say
where each of the following
variables is visible: i, j, newSize, size.
\begin{verbatim}
01 class UnitMatrix {
02 int size;
03
04 void setSize(int newSize) {
05 this.size = newSize;
06 }
07
08 void print() {
09 for (int i = 0; i < size; i++) {
10 for (int j = 0; j < size; j++) {
11 if (i == j) {
12 println("1 ");
13 } else {
14 println("0 ");
15 }
16 }
17 println ""
18 }
19 }
20 }
\end{verbatim}
Check your answers with the faculty members in the lab.
\section{Pointer, arrows\ldots}
\label{sec:pointer-arrowsldots}
\subsection{a)}
Take the example code from the notes:
\begin{verbatim}
01 Point myPoint = new Point();
02 myPoint.x = 0;
03 myPoint.y = 0;
04 int myInt = 0;
05 println "The integer is now " + myInt;
06 println "The point is now " + myPoint.x + "," + myPoint.y;
07 println "Calling method increment(Point, int)..."
08 increment(myPoint, myInt);
09 println "The integer is now " + myInt;
10 println "The point is now " + myPoint.x + "," + myPoint.y;
11
12 class Point {
13 int x;
14 int y;
15 }
16
17 // This method increments the int by 1 and
18 // moves the point to the right
19 void increment(Point point, int n) {
20 n = n + 1;
21 point.x = point.x + 1;
22 point = null;
23 println " At the end of the method..."
24 println " The integer is " + n;
25 println " The point is " + point;
26 }
\end{verbatim}
Write detailed diagrams that show what variables are there in the
``stack'' and what objects they point to in the ``heap'' (if they are
complex types).
\subsection{b)}
\label{sec:bff}
Now do the same for this example code from Day 3:
\begin{verbatim}
01 Person john = new Person();
02 john.name = "John Smith";
03 john.age = 35;
04 Person mary = new Person();
05 mary.name = "Mary Smith";
06 mary.age = 32;
07 Person student = new Person();
08 student.name = "John Smith, Jr.";
09 student.age = 5;
10 student.father = john
11 student.mother = mary
12 println "TEACHER: How old are you, " + student.name + "?"
13 println "LITTLE JOHN: I am " + student.age + " years old, sir.";
14 println "TEACHER: Who is your mother?"
15 println "LITTLE JOHN: " + student.mother.name + ", sir.";
16
17 class Person {
18 int age;
19 String name;
20 Person father;
21 Person mother;
22 }
\end{verbatim}
Check your diagrams with the faculty members in the lab.
\subsection{Flow of execution}
\label{sec:flow-execution}
Look at the following code (with line numbers for clarity):
\begin{verbatim}
01 boolean running = true;
02 while (running) {
03 println "What would you like to do?";
04 println "1 - Enter a new user";
05 println "2 - Delete a user";
06 println "0 - Exit";
07 print "> ";
08 String str = System.console().readLine();
09 int option = Integer.parseInt(str);
10 switch (option) {
11 case 0: running = false;
12 break;
13 case 1: createUser();
14 break;
15 case 2: deleteUser();
16 break;
17 default: println "Invalid option. Please try again."
18 }
19 }
20
21 String requestUser() {
22 String result = System.console().readLine();
23 return result;
24 }
25
26 void createUser() {
27 String user = requestUser();
28 while (!isValidUser(user)) {
29 println("That name is not valid. Please try again.);
30 user = requestUser();
31 }
32 insertUserInDB(user);
33 }
34
35 void deleteUser() {
36 String user = requestUser();
37 while (!isValidUser(user)) {
38 println("That name is not valid. Please try again.);
39 user = requestUser();
40 }
41 if (existsInDB(user)) {
42 deleteUserFromDB(user);
43 } else {
44 println "That user does not exist."
45 }
46 }
47
48 void insertUserInDB(String user) {
49 // do things with DB that we will cover in later weeks
50 }
51 void deleteUserFromDB(String user) {
52 // do things with DB that we will cover in later weeks
53 }
54
55 boolean existsInDB(String user) {
56 // do things with DB that we will cover in later weeks
57 }
58
59 boolean isValidUser(String login) {
60 boolean result = true;
61 for (int i = 0; i < login.length(); i++) {
62 char c = login.charAt(i);
63 if (!Character.isLetter(c) || !Character.isLowerCase(c)) {
64 result = false;
65 }
66 }
67 return result;
68 }
\end{verbatim}
Follow the execution of the code as the user enters the following
sequences of inputs:
\begin{itemize}
\item 4, 0
\item 1, john, 0
\item 1, john smith, johnsmith, 0
\item 2, userNotInDB, usernotindb, 0
\item 1, john, 2, john, 0
\end{itemize}
% TODO: put code with repeated code and make them make a version with
% methods.
\section{Binary and decimal}
\label{sec:from-10011-19}
Create a program in which you define the following methods:
\begin{description}
\item[power(int, int): ] Takes a base $b$ and an
exponent $e$ from the user, and returns the result of $b^e$.
\item[power2(int): ] Takes an exponent $e$ from the user and returns the
result of $2^e$. This method must call the previous one to find out
the result.
\item[binary2decimal(String):] Takes from the user a binary number
(with digits 0 and 1) and returns the corresponding number in
decimal (base-10, with digits between 0 and 9). Hint: in the same
way that you know that $35 = 3 \cdot 10^1 + 5 \cdot 10^0$, you can find that
$100011 = 1 \cdot 2^5 + 1 \cdot 2^1 + 1 \cdot 2^0$. This method must
call the previous one to find out the result.
\item[decimal2binary(int):] The opposite of the previous one: takes a
decimal number and returns the corresponding binary number. Hint:
instead of multiplying by 2, you will need to divide by two this
time (the quotients and the last remainder will give you the binary
number).
\end{description}
The program must offer a menu to the user with two options.
The first one takes a binary number from the
user and returns the corresponding decimal number. The second one does
the opposite: takes a decimal number and returns a binary number. The
program should use the methods defined.
\section{Binary and hexadecimal (*)}
\label{sec:c}
Binary numbers can be quite long. A 32-bit memory address looks like
1001 0101 0110 1010 1011 0010 1001 1010, which is difficult to
handle. That is why memory addresses and other binary numbers are
usually written as \emph{hexadecimal} numbers. An hexadecimal number
is a base-16 number, with digits between 0 and f (f is equivalent to
decimal 15, e is equivalent to decimal 14, and so on). An hexadecimal
number is equivalent to a four-digit binary number, which makes them
quite compact. The former address reads 956ab29a, which is easier to
read and write. To prevent confusion with decimal numbers, hexadecimal
numbers are usually prefixed by ``0x'', as in 0x95 (which is 149) or
0xff (which is 255).
Write a program that takes a String. The string can be a decimal or a
hexadecimal number (starting by ``0x''). Your program must recognise
the number as what it is and convert it to the other base. Use two
methods for conversion as in the former exercise.
\section{More on points}
\label{sec:more-points}
Write a program in which you create and use a class called Point,
with two fields of type double (e.g.~x, y) and the
following methods:
\begin{description}
\item[distanceTo(Point): ] calculates the distance to another point.
\item[distanceToOrigin(): ] calculates the distance to the
origin. Implement it by calling the first method.
\item[moveTo(double x, double y): ] changes the coordinates of this point to
be the given parameters x and y.
\item[moveTo(Point): ] changes the coordinates of this point to move
where the given point is.
\item[clone(): ] returns a copy of the current point with the same
coordinates.
\item[opposite(): ] returns a copy of the current point with the
coordinates multiplied by $-1$.
\end{description}
Two methods in a class can have the same name (identifier) as long as
their parameters are different. This is called \emph{method
overloading} and we will see more of that in the future.
\section{Integer}
\label{sec:integer}
Create your own version of boxed \verb+int+! Create a class Integer2
with only one field (\verb+int value+) and the following methods:
\begin{description}
\item[getValue(): ] returns the value of this number as an
\verb+int+, a getter.
\item[setValue(int): ] a setter.
\item[isEven(): ] returns true if the number is even, false
otherwise.
\item[isOdd(): ] the opposite.
\item[prettyPrint(): ] prints the value of the integer on the screen.
\item[toString(): ] returns a String equivalent to the number.
\end{description}
Check that it works by using the following program:
\begin{verbatim}
Integer2 i2 = new Integer2();
print "Enter a number: ";
String str = System.console().readLine();
int i = Integer.parseInt(str);
i2.setValue(i);
print "The number you entered is "
if (i2.isEven()) {
println "even.";
} else if (i2.isOdd()) {
println "odd.";
} else {
println "undefined!! Your code is buggy!";
}
int parsedInt = Integer.parseInt(i2.toString());
if (parsedInt == i2.getValue()) {
println("Your toString() method seems to work fine.");
}
\end{verbatim}
\section{A bit more practice with doubles}
\label{sec:bit-more-practice}
The goal of this exercise is providing additional practice with
double-precision numbers.
Write a program that asks the user for the total amount borrowed for a
mortgage, the number of years to pay it back, and the interest rate
(in this exercise, we assume it is a fixed
rate). The program can then calculate how much must be paid at the end
$$t = c \cdot \left(1+ {r \over 100}\right)$$
where $t$ is the total, $c$ is the cost,
and $r$ is the rate as a percentage. The program should print:
\begin{itemize}
\item The total amount to be paid
\item The money to be paid every year
\item The number of years before the interest is paid and only the
initial capital remains
\end{itemize}
Write a method to calculate each piece of data.
% TODO: think this through
%
% \section{A mortgage program with variable rates (*)}
% \label{sec:bit-more-practice}
% Write a program that asks the user for the total amount borrowed for a
% mortgage, and the number of years to pay it back.
% Once this is done, the program must enter a loop in which every
% iteration is a year. For every year, the program must request the
% interest rate for that year.
% and the amount payed by the user, and
% calculate
% \begin{itemize}
% \item If the amount if less than the interest to be payed that year,
% the program must complain and ask for a higher amount.
% \item If the amount is exactly the interest to be paid that year,
% nothing else happens until next year.
% \end{itemize}
% , and the amount payed every year. The
% program must
% Interest on an account
% Fixed rate Mortgage: calculate number of years, and how much you pay
% per month and in total.
% (*) Variable rate mortgage: change rate every year and estimate number
% of years left, total number of years, and how much you pay per
% month, and how much you pay in total.
\end{document}