Homework2_3015218122_戎达

程序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

Fault:第一个值总读不到,应将i<0改为i<=0

不执行错误的用例:  x为空数组即可

执行错误但不产生错误状态:test: x=[3, 2, 5]; y = 2

产生错误状态但不影响结果:test: x=[3, 5]; y = 2

程序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

Fault:数组遍历顺序有误,每次找到的是第一个索引值

不执行错误的用例:  x为空数组

执行错误但不产生错误状态:test: x=[3, 0, 5]

产生错误状态但不影响结果:test: x=[3, 5]

 

posted on 2018-03-11 22:17  IamRadar  阅读(110)  评论(0)    收藏  举报

导航