HomeWork2

程序一:

复制代码
 1 public intfindLast(int[] x, inty) {
 2 //Effects: If x==null throw NullPointerException
 3 // else return the index of the last element
 4 // in x that equals y.
 5 // If no such element exists, return -1
 6     for (int i=x.length-1; i> 0; i--)
 7     {
 8         if (x[i] == y)
 9         {
10             return i;
11          }
12     }
13     return -1;
14 }
15 // test: x=[2, 3, 5]; y = 2
16 // Expected = 0                    
复制代码

fault: for循环的终止条件应为i>=0并非i>0

1.If possible, identify a test case that does not execute the fault. (Reachability) 即不会执行fault的case:

x为null, y随意。由于x为null,for循环的变量i的赋值会因为null没有length所以抛出NullPointerException,不会到达fault的位置

期望值: NullPointerException

实际值: NullPointerException

2. If possible, identify a test case that executes the fault, but does not result in an error state.即执行了错误的代码但是没有出现error:

执行到fault但是并没有error的样例: x=[1,2,6,4,8] , y=2。 由于在i=1的时候就会因x[1]==y而终止循环,所以虽然每次for循环都会执行i>0的判断(执行fault),但是并没又因此而出现error(没有error是因为这个样例里并没有因为i>0这一fault而终止循环,即出现内部问题)。

3. If possible identify a test case that results in an error, but not a failure.即出现了error但是结果没有出错:

处于error但无failure的样例:x=[1,2,3,4,5] y=0。 由于y根本就不在x中,因此虽然程序跳出循环是因为fault(此时处于了error状态),但是结果仍是没找到,返回了-1.

程序二:

复制代码
 1 public static intlastZero(int[] x) {
 2 //Effects: if x==null throw NullPointerException
 3 // else return the index of the LAST 0 in x.
 4 // Return -1 if 0 does not occur in x
 5     for (int i= 0; i< x.length; i++)
 6     {
 7         if (x[i] == 0)
 8         {
 9             return i;
10         }
11     } return -1;
12 }
13 // test: x=[0, 1, 0]
14 // Expected = 2    
复制代码

fault: for循环的搜索顺序应该从大到小。即 for (int i=x.length-1; i>= 0; i--)

不会执行fault的样例: 不存在,所有的样例都会进入到for循环,一旦开始了i=0的赋值,就进入了fault

执行到fault但是并没有error的样例: x=[0] 。 由于数组的长度为1,所以这时就没有了从大到小或从小到大的概念了。fault不会引起error

Excepted: 0

Actual: 0

处于error但无failure的样例:x=[1,2,0,3,4] 。 由于检索的顺序反了,所以只要是数组内元素个数多于一个,就是处于error,但是结果没变。

Excepted: 2

Actual: 2

原文地址:https://www.cnblogs.com/lushilin/p/5255054.html