CSA Unit 4 Lesson 7
Name(s) __________________________________________________ Period _______ Date _____________________
[KEY] Extra Practice - Nested If Statements
Check for Understanding
Consider the following method.
public static void mystery(int a, int b, int c) {
if (a < 10) {
if (b < 10) {
System.out.print("X");
}
System.out.print("Y");
}
if (c < 10) {
if (b > 10) {
System.out.print("Y");
}
else {
System.out.print("Z");
}
}
}
What is printed as a result of the call mystery(5, 9, 5)?
A. XY
B. XYZ
C. Y
D. YY
E. Z
1
AP Exam Prep
Consider the following code segment. Assume num is a properly declared and initialized int variable.
if (num > 0) {
if (num % 2 != 0) {
System.out.println("A");
}
else {
System.out.println("B");
}
}
Which of the following best describes the result of executing the code segment?
A. When num is a negative odd integer, "B" is printed; otherwise, "A" is printed.
B. When num is a negative even integer, "B" is printed; otherwise, nothing is printed.
C. When num is a positive even integer, "A" is printed; otherwise, "B" is printed.
D. When num is a positive even integer, "A" is printed; when num is a positive odd integer, "B" is
printed; otherwise, nothing is printed.
E. When num is a positive odd integer, "A" is printed; when num is a positive even integer, "B" is
printed; otherwise, nothing is printed.
2
Extra Practice
Do This: A citizen science project is looking to inventory all of the trees in New York City. They would like to
allow citizens to use an app to inventory trees based on species and location. They do not want two people to
enter the same tree into their system and will determine whether this has occurred by comparing the latitude
and longitude. Write a class called Tree with the following specifications:
Instance Variables:
● species - String
● latitude - double
● longitude - double
Accessor methods for:
● latitude
● longitude
An equals() method which compares two trees based on their latitude and longitude.
One possible solution:
public class Tree {
private String species;
private double latitude;
private double longitude
public Tree(String species, double latitude, double longitude) {
this.species = species;
this.latitude = latitude;
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public boolean equals(Object other) {
if (other != null) {
if (latitude == ((Tree) other).getLatitude()) {
if (longitude == ((Tree) other).getLongitude()) {
return true;
}
}
}
return false;
3
}
}