In: Computer Science
1. Using the following code identify the fault.
2. Using the following code indentify a test case that results in an error, but not a failure.
public static int lastZero (int[] x) {
//Effects: if x == null throw NullPointerException
//else return the index of the last 0 in x.
//Return -1 if 0 does not occur in x
for (int i = 0; i < x.length; i++)
{
if (x[i] == 0)
{
return i;
}
}
return -1;
}
//test: x = [0, 1, 0]
// Expected = 2
Here is code:
public static int lastZero (int[] x) {
//Effects: if x == null throw NullPointerException
//else return the index of the last 0 in x.
//Return -1 if 0 does not occur in x
if(x == null)
throw new NullPointerException("The x is null");
else
{
//loops from last index to 0th index
for (int i = x.length - 1; i >= 0; i--)
{
if (x[i] == 0)
{
return i;
}
}
return -1;
}
}
Sample test case to run:
public class testCase {
public static void main(String []args){
int[] a = {0,1,0};
System.out.println(lastZero(a));
}
public static int lastZero (int[] x) {
//Effects: if x == null throw NullPointerException
//else return the index of the last 0 in x.
//Return -1 if 0 does not occur in x
if(x == null)
throw new NullPointerException("The x is null");
else
{
//loops from last index to 0th index
for (int i = x.length - 1; i >= 0; i--)
{
if (x[i] == 0)
{
return i;
}
}
return -1;
}
}
}
Output:
2