Ron Dai Learn Java With Math Using Fun Projects and Games Apress 2020 3 PDF
Ron Dai Learn Java With Math Using Fun Projects and Games Apress 2020 3 PDF
IOU Computation
IOU means “Intersection Over Union.” It is used as a metric in image
detection technology. This metric computes a ratio of the overlap area
between two rectangles over their union area. For simplicity, the two
rectangles are in the same direction, as you will see R1 and R2 in Figure 31-1.
To figure out this ratio, we need to find out their overlap area named X.
If the areas for the two rectangles are R1.area and R2.area, then
Figure 31-2. Two rectangles that are apart from each other
It will be when:
If one of the conditions from (1) to (4) is valid, the overlap area is 0.
Next, we notice that the overlap area is actually surrounded by four
lines, as shown in Figure 31-3.
204
Chapter 31 IOU Computation
205
Chapter 31 IOU Computation
206
Chapter 31 IOU Computation
Math.max(r1.y_min,
r2.y_min),
Math.min(r1.y_max, r2.y_
max));
System.out.println(overlapArea + " / (" + areaR1
+ " + " + areaR2 + " - " +
overlapArea + ")");
return overlapArea / (areaR1 + areaR2 -
overlapArea);
}
We are not done yet. We need to always think about how to improve
our class design and optimize code. In the Rectangle class, there are
getWidth() and getHeight() methods. What if we add a method called
getArea() to the Rectangle class?
The Rectangle class is updated as:
import java.lang.Math;
public class IntersectionOverUnion {
public static void main(String[] args) {
// test case 1
Rectangle r1 = new Rectangle(3f, 2f, 5f, 7f);
Rectangle r2 = new Rectangle(4f, 1f, 6f, 8f);
System.out.println("IOU=" + getIOU(r1, r2));
208
Chapter 31 IOU Computation
209
Chapter 31 IOU Computation
210
CHAPTER 32
Projects
I want to recommend a list of hands-on projects for you to practice
independently. Working through these projects will definitely help you
deepen your understanding of the basic Java programming concepts
described in this book.
P
roject A
S
tep 1
Write a class called Rectangle that represents a rectangular two-
dimensional region. The constructor creates a new rectangle whose top-
left corner is specified by the given coordinates and with the given width
and height.
"Rectangle[x=1,y=2,width=3,height=4]"
Step 2
Add the following accessor methods to your Rectangle class from the
previous exercises:
212
Chapter 32 Projects
Project B
Design a program to find the number of days between the current day and
the user’s birthday, given four input values.
The program prompts for the user’s birthday. The prompt lists the
range of values from which to choose. Notice that the range of days printed
is based upon the number of days in the month the user typed. The
program prints the absolute day of the year for the birthday. January 1st is
absolute day #1 and December 31st is absolute day #365. Last, the program
prints the number of days until the user’s next birthday. Different messages
appear if the birthday is today or tomorrow. The following are four runs of
your program and their expected output (user input data is right after the
‘?’ mark):
Project C
The game rule is this: you start with 21 sticks, and two players take turns
either taking one or two sticks. The player who takes the last stick loses.
Can you design a program to simulate one of the two players in the game?
One player is a user and the other player is the computer.
213
Chapter 32 Projects
Project D
Write a method named hasVowel() that returns whether a string has
included any vowel (a single-letter string containing a, e, i, o, or u, case-
insensitively).
Project E
Write a method named gcd() that accepts two integers as parameters and
returns the greatest common divisor (GCD) of the two numbers. The GCD
of two integers a and b is the largest integer that is a factor of both a and b.
The GCD of any number and 1 is 1, and the GCD of any number and 0 is
the number.
One efficient way to compute the GCD of two numbers is to use
Euclid’s algorithm, which states the following:
GCD(A, B) = GCD(B, A % B)
GCD(A, 0) = Absolute value of A
For example:
• gcd(0, 8) returns 8
Project F
Write a method named toBinary() that accepts an integer as a parameter
and returns a string of that number’s representation in binary. For
example, the call of toBinary(42) should return “101010”.
214
Chapter 32 Projects
Project G
Use the four numbers on the following cards to create a math expression
that equals 24. Each card can be used only once. Treat ace as a number
“1”. You may use +, -, *, /, ( and ) in the math expression. Please find all
possible answers.
215
CHAPTER 33
Java Intermediate
Solutions
For your reference, in this chapter I’ll provide you with answer hints to
some of the problems in the earlier chapters. For example, “For 16.” means
“Hints for problems in Chapter 16.”
218
Chapter 33 Java Intermediate Solutions
if (a == 0) {
if (b == 0) {...}
else {...}
} else {
if (b != 0) {...}
}
219
Chapter 33 Java Intermediate Solutions
case 'C':
default:
System.out.println("Some other color");
break;
}
220
Chapter 33 Java Intermediate Solutions
1 1 1 1
e =1+ + + +¼
1! 2 ! 3 ! r!
2. b)
3.
4. (A), (D)
5. (B)
221
Chapter 33 Java Intermediate Solutions
2.
@Override
public double getArea() {
return PI * this.radius * this.radius;
}
}
222
Chapter 33 Java Intermediate Solutions
2. { 0, 4, 0, 0, 11, 0, 0, 2 }
223
Chapter 33 Java Intermediate Solutions
224
Chapter 33 Java Intermediate Solutions
225
Chapter 33 Java Intermediate Solutions
226
Index
A Collatz conjecture
defining, 5
Abstraction, 171, 182
program, 5, 6
Algorithms
Collinearity, 107
creation, real-world
Conditional operators, 64–67
objects, 39, 40
Conditional statements, 218, 219
swap values, 40–41
bigger number identification, 109
Array, 223
example, 111, 114
character, 185
if clauses, 112
data types, 185
if/else if structure, 110
defined, 185
if/else structure, 109, 110
element values, 186
nested if/else structure, 110
index, 185
quadrants, 114, 115
size, 186
tree-like structure, 111
contains() method, 213
B convertToBaseN() method, 144
Basic projects, 85–87 countBase10Numbers() method, 143
Counting, 220
countNumbers2(), 136
C for-loop, 137, 139, 140
class instantiation, 29 isDistinct(…), 135
Class variables/instance single loop, 131
variables, 33 switch statement, 145
Coding mistakes, 73, 74 tables, 132
Coding structure, 81 tickets, 131
Coin flip game, 93, 94, 96 Curly braces, 82
D example, 53
exp() method, 54
Design considerations
list of numbers, 53
Demo class, 199
structure, 49
Game class, 195, 196
main() method, 199
MyClass class, 197, 198 G
Rectangle class, 193–195
gcd() method, 214
static fields, 199
General rules
test class, 200
conditional operation, 80, 81
double getSlope() method, 105
input in console, 80
do-while loop, 60–61
output in console, 79
repeat an operation, 80
E variable name, 79
getSlope() method, 106
Encapsulation, 181, 182, 222
Getters method, 163
Error correction, 77, 78
Greatest common divisor (GCD), 214
Exception handling, 76–77
F H
hasVowel() method, 214
Factorization
Hexadecimal–base 16 number
definition, 147
system, 15
finding factors, 147, 148
iterations, 149
square root, 150–153 I
Fields, 163 if/else structure, 64, 109, 120
for loop if structure, 63
arithmetic sequence, 51 Inheritance, 221
counting strategy, 51, 52 Car class, 177
example, 49, 50 Driver class, 178
formula, 50, 51 isFourWheelDrive() method, 177
list of numbers, 54 Sedan class, 177, 178
Math Input, read user data, 44
228
INDEX
229
INDEX
O algorithm, 157
Calculus, 161
Object-Oriented programming, 221
for-loop, 159
access modifiers, 164
Java programming, 161
Account class, 169
long value type, 159, 160
characteristics, 163–165
main method(), 158
class vs. object, 166, 167
Math.random() method, 158
field vs. parameter, 169
population
Game class, 168
calculation, 155, 156
Name class, 166
Pitfalls, 189–191, 223–226
non-fields, 166
Point class, 106, 212
NumberHolder class, 168
Polymorphism, 183, 222
Point class, 167
Primitive types, 35–36
public int getAge() method, 164
Programming tips, 75, 76
public Student() method, 164
Properties, 163
structural view, 165
Pythagorean
public String getFirstName()
primes, 101
method, 164
triples, 97–101, 217
public String getLastName()
method, 164
public void setAge(int age) R
method, 164
Rectangle class, 211, 212
Vehicle class, 166
Reference types, 36
Octal–base 8 number system, 16
reverse() method, 142
Output
System.out.println, 44, 45
example, 45 S
problems, 47 Scanner utility class, 43
special characters, 44 Setters method, 163
Slope of a line, 105, 106
P, Q Source, 25
Package, 25 Stick game, 213
Pi experimentation, 221 StringBuffer class, 142
230
INDEX
231