Liam Liam - 1 month ago 8
Java Question

Need to fix a test case in java

What the code is suppose to do: return an array of just the odd numbers in the given integer array.

The problem I have: The answer I get for the test case is correct. However, it keeps saying that the test case failed and that the expected answer is the one I actually got.

The code I have is:

public int[] justTheOdds(int[] array)

{
int[] onlyOdds = new int[array.length];
for(int i = 0; i < array.length; i++)
{
if(array[i] % 2 != 0)
{
onlyOdds[i] = array[i];
}
}
return onlyOdds;
}


Here's my test case (in the main method in a different class):

System.out.println("\n-------- Testing the justTheOdds method --------\n");

//first test
num1 = new int[] {5, 2, 3};
int[] odds = {5, 3};
int[] answer = srvObj.justTheOdds(odds);

passFailMsg = (Arrays.toString(odds) == Arrays.toString(answer) ? " Pass : ":"*FAIL* : ");

outMsg = "justTheOdds( " + Arrays.toString(num1) + " ) --> " + Arrays.toString(answer);

expMsg = (Arrays.toString(num1) == Arrays.toString(answer) ? "": ", should be " + Arrays.toString(odds));

System.out.println(passFailMsg + outMsg + expMsg);


When I run my program this is what happens:

-------- Testing the justTheOdds method --------

*FAIL* : justTheOdds( [5, 2, 3] ) --> [5, 3], should be [5, 3]


I'm really unsure of how to fix this. Any and all help will be appreciated. Thanks.

Answer
Arrays.toString(odds) == Arrays.toString(answer)

You cannot compare Strings like that in Java, use equals.

You could also compare the two arrays directly, but then neither == nor equals works, so you have to say

Arrays.equals(odds, answer)

Also, when writing tests, you should use a test framework such as JUnit. That saves time and gives you nice reports. It also has an assertArrayEquals that knows how to compare arrays and produce a meaningful error message that shows where the difference occurred.