代码运行的结果与预期不同,输出值为-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;
出现与预期结果不同的情况是因为源代码判断的是出现第一个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三者之间的关系有了进一步的了解和区分。
转载于:https://www.cnblogs.com/jingyizhang/p/8566317.html
相关资源:数据结构—成绩单生成器