10.8.4. Hard Multiple Choice QuestionsΒΆ
These problems are about the same or harder than those that you will typically see on the AP CSA exam.
- The string
s
contains two or more of the same characters. - It is not enough for
s
to contain two of the same characters, they must be adjacent to satisfys.charAt(0) == s.charAt(1)
. - The string
s
starts with two or more of the same characters. - It is not neccessary for the adjacent characters to be at the start of the string.
- The string
s
contains two or more of the same character that are next to each other. - This method will return true when
s
has at least 2 characters in it and at least 2 characters are the same and are adjacent. - The string
s
ends with two or more of the same characters - It is not neccessary for the adjacent characters to be at the end of the string.
10-7-4-1: Given the following method declaration, this method will return true if and only if:
public static boolean check(String s)
{
return s.length() >= 2 &&
(s.charAt(0) == s.charAt(1) ||
check(s.substring(1)));
}
You can step through the code above by clicking on the following link Ex-11-8-1.
- 5
- The first time the method is called,
i
is not equal to 0, so the method makes a recursive call to itself, with the value of 82/3 which equals 27 due to integer division. This is still not equal to 0, so the method calls itself with the first parameter equal to 9, then 3, then 1. Finally, the method is called with the first parameter of 1/3 which equals 0 due to integer division which throws away any decimal part. Each method call adds 1 to the result, except for the final call wheni
is equal to 0. - 4
- Each time the method is called when
i
is not equal to 0, the return value is incremented. This happens 5 times, withi
equal to 81, 27, 9, 3, and 1. - 6
- The return value is not incremented the last time the method is called, when
i
is equal to 0. - 7
- The method only executes 6 times, with the return value incremented each time
i
is not equal to zero - The method never returns due to infinite recursion.
- Infinite recursion would happen if the method never reached its base case where
i
is equal to 0. This would be true if the division could result in a constantly shrinking fraction, but integer division truncates the fractional portion of the division.
10-7-4-2: Given the following method declaration, what will redo(82, 3)
return?
public static int redo(int i, int j)
{
if (i == 0)
{
return 0;
}
else
{
return redo(i / j, j) + 1;
}
}
You can step through the code above by clicking on the following link Ex-11-8-2.
You have attempted of activities on this page