homework2
Question1:
public int findLast (int[] x, int y)
{ 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
- The fault is happen in i > 0, When the program iteration to i = 1, test 3 is not equal to 2.It should be go on to test i=0, but because the wrong test condition, it will be stop at i=1, and return -1;
- Let X is null
- Test x = [3, 2, 5]; y = 2,//Expected = 1;
- Test x = [1,1, 1]; y = 2,//Expected = -1;The program will execute and return the truth, but it has error.
Question2:
public static int lastZero (int[] x)
{ for (int i = 0; i < x.length; i++)
{ if (x[i] == 0) { return i; } } return -1; }
// test: x=[0, 1, 0] // Expected = 2
- The fault is happen in int i = 0; By execute this program, it will be start at i=0, but the request is to find a last zero position. By the test, it will return 0, the first 0 position.
- Let X is null
- Test x = [1, 2, 0]; //Expected = 2;
- Test x = [1, 1, 1]; //Expected = -1; The program will execute and return the truth, but it has error.
浙公网安备 33010602011771号