hw2- 找出下面两个程序中的错误

下面是第一题的题目:

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.

(1) Identify the fault.
(2) If possible, identify a test case that does not execute the
fault. (Reachability)
(3) If possible, identify a test case that executes the fault, but
does not result in an error state.
(4) If possible identify a test case that results in an error, but
not a failure

1.
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

答:

(1)在这个程序中并没有测试到数x中的最开始的一个x[0],如果x[0]刚好等于y而之前的不等于那么结果就会出现偏差!

(2)text:x=[0,5,2]; y = 2

(3)text:x=[1,3,4]; y = 2

(4)text: x=[2,1,0]; y = 2

第二题:

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

答:

(1)这个程序只会显示第一个x=0的下标而不是最后一个

(2)case text: x=[0,1,2]

(3)case text: x=[1,2,2]

(4)case text:x=[0,0,0]

posted @ 2017-03-02 20:46  兰迪  阅读(162)  评论(0)    收藏  举报