Below are two faulty programs. Each includes a test case that results in failure. Answer the following questions (in the next slide) about each program.
public int findLast (int[] x, int y) { //Effects: If x==null throw NullPointerException // else return the index of the last element // in x that equals y. // If no such element exists, return -1 for (int i=x.length-1; i > 0; i--) { if (x[i] == y) { return i; } } return -1; } // test: x=[2, 3, 5]; y = 2 // Expected = 0
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
-
- Identify the fault.
第一个:在递减的过程中没有遍历到0便结束循环导致循环不完整
for (int i=x.length-1; i > 0; i--)
应改正为
for (int i=x.length-1; i >= 0; i--)
第二个:遇到符合条件的直接结束函数,不考虑之后的内容了,即返回第一个0,不返回最后一个0
for (int i = 0; i < x.length; i++)
应改正为
for (int i = x.length-1; i >= 0; i--)
- If possible, identify a test case that does not execute the fault. (Reachability)
第一个:(不让它执行到该语句)test: x=[], y=1
第二个:(同样不让它执行到该语句)test:x=[]
- If possible, identify a test case that executes the fault, but does not result in an error state.
第一个:test: x=[3,4,5], y=4 结果正确,并且也执行了fault
第二个:test: x=[1,0,1], Expected: 1
- If possible identify a test case that results in an error, but not a failure.
第一个:test: x=[3,4,5], y=2, 返回-1
第二个:test: x=[1,2,3], Expected: -1