All AP Computer Science A Resources
Example Questions
Example Question #1 : Logic Errors
Consider the following code:
public static int[] del(int[] a,int delIndex) {
if(delIndex < 0 || delIndex >= a.length) {
return null;
}
int[] ret = new int[a.length - 1];
for(int i = 0; i < a.length; i++) {
if(i != delIndex) {
ret[i] = a[i];
}
}
return ret;
}
What is the error in the code above?
There is a null pointer exception.
You need to implement a swap for the values.
The use of the array index i is incorrect.
The loop is infinite.
The intial conditional (i.e. the if statement) has incorrect logic.
The use of the array index i is incorrect.
The problematic line in the code above is the one that reads:
ret[i] = a[i];
This is going to work well until the end of the array. The variable i is going to go for the length of the array a. However, the array ret is one less in length. This means that you will overrun your array, getting an ArrayIndexOutOfBoundsException at the very end of the looping. You would need to implement two indices—one of which will not be incremented on that one time when you skip the element that is removed from the array.
Example Question #1 : Logic Errors
What is wrong with this loop?
int i = 0;
int count = 20;
int[] arr = [1, 3, 4, 6, 8, 768, 78, 9]
while (i < count) {
if (i > 0) {
arr[i] = count;
}
if (i < 15) {
System.out.println("HEY");
}
}
The loop is infinite
it prints Hey too many times
if statement is incorrect
count never gets decremented
The loop is infinite
The loop is infinite because i never gets incremented to become greater than count.
The loop in this case is,
while (i < count) {
if (i > 0) {
arr[i] = count;
}
and the error occurs because there is no terminating factor in the while loop. A terminating factor would be,
while(i<count){
if(i>0, i<10, i++){
arr[i] = count;
}
All AP Computer Science A Resources
![Learning Tools by Varsity Tutors](https://vt-vtwa-app-assets.varsitytutors.com/assets/problems/og_image_practice_problems-9cd7cd1b01009043c4576617bc620d0d5f9d58294f59b6d6556fd8365f7440cf.jpg)