st-homework2
第一段代码分析
1 public static int findLast(int[] x,int y) { 2 //Effects:If x == null throw 3 // NullPointerException 4 //else return the index of the last element 5 //in x that equals y. 6 //If no such element exists, return -1 7 for(int i=x.length-1;i>0;i--) { 8 if(x[i]==y) { 9 10 return i; 11 12 } 13 } 14 15 return -1; 16 } 17 //test:x=[2,3,5];y=2; 18 //Expected = 0;
分析:
代码运行的结果与预期不同,输出值为-1。出现这种情况的原因在于,程序中的for循环语句出现错误,i>0应改为i>=0,因为如果是按照原程序的i>0则无法判断x数组的第一位是否等于y的值,导致最后运行结果出现偏差。
用可以正常运行的test case进行测试:
1 public class findLast { 2 public static int findLast(int[] x,int y) { 3 //Effects:If x == null throw 4 // NullPointerException 5 //else return the index of the last element 6 //in x that equals y. 7 //If no such element exists, return -1 8 for(int i=x.length-1;i>0;i--) { 9 if(x[i]==y) { 10 System.out.println(i); 11 return i; 12 13 } 14 } 15 System.out.println(-1); 16 return -1; 17 } 18 //test:x=[3,2,5];y=2; 19 //Expected = 1; 20 public static void main(String[] args){ 21 int[] x = {3,2,5}; 22 int y=2; 23 findLast(x,y); 24 } 25 }
输出结果正确:
这种情况符合“a test case that executes the fault, but does not result in an error state ”;
同理,可以找出符合“a test case that does not execute the fault”的 test case 为:x=[ ];y=2;Expected=NullPointerException;
"a test case that results in an error, but not a failure" can be :x=[3,4,5];y=2;Expected=-1;
第二段代码分析
1 public class lastZero { 2 public static int lastZero(int[] x) { 3 //Effects: if x == null throw 4 //NullPointerException 5 //else return the index of the LAST 0 in x. 6 //Return -1 if 0 does not occur in x 7 for(int i=0;i<x.length;i++) { 8 if(x[i]==0) { 9 System.out.println(i); 10 return i; 11 } 12 } 13 System.out.println(-1); 14 return -1; 15 } 16 //test: x=[0,1,0] 17 //Excepted = 2 18 public static void main(String[] args){ 19 int[] x = {0,1,0}; 20 lastZero(x); 21 } 22 }
结果:
分析:
出现与预期结果不同的情况是因为源代码判断的是出现第一个0的位置而不是最后一个0的位置,不应该在第一次出现x[i]==0的情况后就直接返回i,而应该继续往后寻找,直到到达x的最后一位,在选取最大的i输出。
符合“a test case that executes the fault, but does not result in an error state ”的test case为:x=[1,2,0];Expected=2;
符合“a test case that does not execute the fault”的 test case 为:x=[ ];Expected=NullPointerException;
"a test case that results in an error, but not a failure" can be :x=[1,2,0,1,2];Expected=2;
总结
对failure、fault和error三者之间的关系有了进一步的了解和区分。