Problem Description

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.

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
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  
Questions
  • 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.

Solutions

The 1st

  1). 故障(Fault):循环控制元素应为i >= 0.

  2). 当x为空时代码不会抵达错误地点。

  3). 当x中等于y的最后一个元素不是x[0]时,如x = [1, 5, 9, 6, 87, 9, 54], y = 9时,虽然运行到了出错代码,但并不会出现错误结果。

  4). 当x中只有一个元素时,会永远返回-1;当x = [8], y = 8时,出现Error和Failure;当x = [8], y = 3时,出现Error,但没有Failure。

The 2nd

  1). 故障(Fault):循环控制元素应为for (int i = x.length; i >=0; i--).

  2). 程序总会抵达错误地点。

  3). 当x中只有一个元素时,如x = [1]时,虽然运行到了出错代码,但并不会出现错误。

  4). 当x中只有一个0或没有0时,如当x = [8,0,5,4]时,程序运行出现Error,但没有Failure。

posted on 2017-03-05 00:00  Jarin_Wei  阅读(91)  评论(0编辑  收藏  举报