1 public int findLast (int[] x, int y) {
 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
 1 public static int lastZero (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 } 
12     return -1;
13 }
14 // test: x=[0, 1, 0]
15 // Expected = 2

问题及答案:

1.Identify the fault.

第一个程序中的

for (int i=x.length-1; i > 0; i--)

i>0,使得程序不能完全遍历数组中的所有元素应该更正为i>=0;此时才能完全遍历数组中的所有元素。

第二个程序中

for (int i = 0; i < x.length; i++)

出现了问题,此时查找是从头开始查找,如果输入中有多个0出现则会返回第一个0所处的位置,而题目要求是返回最后一个0所在的位置,

因此应该将循环条件改为

for (int i = x.length-1; i >=0; i--)

 

2. If possible, identify a test case that does not execute the fault. (Reachability)

第一个程序中可以选用:

// test: x=[5,2,4,7,9]; y = 7
// Expected =3

 第二个程序中可以选用:

// test: x=[5,0,4,7,9];
// Expected =1

3. If possible, identify a test case that executes the fault, but does not result in an error state.

第一个程序可以使用:

// test: x=[2,3,5,8,9,6]; y = 10
// Expected =-1

 第二个程序中可以选用:

// test: x=[5,2,4,7,9]; 
// Expected =-1

 

4.If possible identify a test case that results in an error, but not a failure

第一个程序可以使用

// test: x=[2, 3, 5]; y = 2
// Expected = 0

 第二个程序中可以选用:

// test: x=[5,2,4,0,0]; 
// Expected =4

 


posted on 2017-02-25 21:31  徐胖胖  阅读(180)  评论(0编辑  收藏  举报