觀察兩段代碼並回答下列問題:
(1) 發現錯誤代碼;
(2) 試着編寫測試用例,不執行fault部分;
(3) 執行fault部分,但不出現error情況;
(4) 出現error情況,但不發生failure。
代碼一:
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) for循環的終止條件應該為i<=0;
(2) x=[],y=2;
這裏由於x為空,所以不進入for循環,直接返回NullPointerException;
Excepted:NullPointerException,
Actual:NullPointerException;
(3) x=[1,2,3],y=2;
這裏最後一個等於y的值不在x[0]處,而在x[1],所以for循環並沒有執行到"i>=0"的條件出,所以不會出現error狀態;
Excepted:1,
Actual:1;
(4) x=[3,4,5],y=2;
這裏雖然執行到了error狀況,但由於x中並沒有與y相等的值,所以得到結果是正確的,所以沒有出現failure;
Excepted:-1,
Actual:-1;
代碼二:
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)for循環執行的方向反了,不應該由i=0開始執行,而應該是從x.length-1開始遞減;
(2)這裏無論如何代碼都會執行進入for循環,所以不存在這樣的樣例;(這裏與上一題不同的地方在於,上一問中的fault是for循環的一個判斷條件,當x為空時,for循環在執行第一步對i賦值是便會出現NullPointerException,進而不會執行到fault;而這一問中的fault是整個for循環,所以只要進入for循環就屬於進入了fault中)
(3)x=[1];這裏執行時會進入for循環,即進入了fault,但是由於x中只有一個元素,所以不存在循環執行的正反問題,所以沒有error狀態;
Excepted:-1,
Actual:-1;
(4)x=[1,0,2];這裏代碼執行時會發生error狀態,但是由於x中只有一個0,所以無論是正着執行for循環還是倒着執行,都不會對結果產生影響,所以沒有發生failure;
Excepted:1,
Actual:1。