Java Reference
In-Depth Information
answer. In what cases does the method report an incorrect answer? How can the code be changed so that it will
always return a correct result?
public static boolean contains(String str, char ch) {
boolean found = false;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
found = true;
} else {
found = false;
}
}
return found;
}
18. Using “Boolean Zen,” write an improved version of the following method, which returns whether the given String
starts and ends with the same character:
public static boolean startEndSame(String str) {
if (str.charAt(0) == str.charAt(str.length() - 1)) {
return true;
} else {
return false
}
}
19. Using “Boolean Zen,” write an improved version of the following method, which returns whether the given number
of cents would require any pennies (as opposed to being an amount that could be made exactly using coins other
than pennies):
public static boolean hasPennies(int cents) {
boolean nickelsOnly = (cents % 5 == 0);
if (nickelsOnly == true) {
return false;
} else {
return true;
}
}
20. Consider the following method:
public static int mystery(int x, int y) {
while (x != 0 && y != 0) {
if (x < y) {
y -= x;
} else {
x -= y;
}
Search WWH ::




Custom Search