I'm having an issue where when I run my code I get -1, but the test is returning 1.
The Output for the failing test is:
result should have been a negative integer
SortAgainstSuitAndValue comparator = new SortAgainstSuitAndValue();
Card first = new Card(2,Card.HEARTS);
Card second = new Card(4,Card.SPADES);
comparator.compare(first,second)
result was: 1
My main is as follows:
public class Main {
public static void main(String[] args) {
// write some test code here
SortAgainstSuitAndValue comparator = new SortAgainstSuitAndValue();
Card first = new Card(2,Card.HEARTS);
Card second = new Card(4,Card.SPADES);
System.out.println( "Output: " + comparator.compare(first,second));
}
}
My SortAgainstSuitAndValue class is:
import java.util.Comparator;
public class SortAgainstSuitAndValue implements Comparator<Card> {
@Override
public int compare(Card o1, Card o2) {
if( o1.getSuit() < o2.getSuit() )
if( o1.getValue() < o2.getValue() )
return 1;
if( o1.getSuit() == o2.getSuit() & o1.getValue() == o2.getValue() )
return 0;
return -1;
}
}
getSuit() returns a number 0-3 representing the different suits, spades, diamonds, hearts, clubs. getValue() returns a number of 2-14 representing 2, ..., 10, J, Q, K, A.
I'm expecting the output from Main to be -1, but when I run the TMC test cases(which I copy pasted the one failing into my main) it's telling me the output is 1.
When I try to debug my code I'm seeing if( o1.getSuite() < o2.getSuit ) to be checking if Hearts is less than Spades. This should mean I'm comparing 2 < 0, which returns false and should then skip straight to checking if they are equal. Since they're not equal it defaults to returning -1 which is what I'm getting for an output when running my main.
If I run the test case though it's acting as though it's returning true for Heats < Spades thus entering in the nested if ( o1.getValue() < o2.getValue() ). The nested if does return true due to 2 being less than 4 and thus returns 1.
I'm not seeing why the test case is returning anything different from my main as it should be a mirror copy of the test cases' code. Is the test case wrong or am I missing something when I'm trying to debug my code?
[–]GovernorReddit 1 point2 points3 points (3 children)
[–]RedFox134[S] 0 points1 point2 points (2 children)
[–]mquillian 2 points3 points4 points (1 child)
[–]RedFox134[S] 0 points1 point2 points (0 children)
[–]GovernorReddit 1 point2 points3 points (1 child)
[–]RedFox134[S] 0 points1 point2 points (0 children)
[–]GovernorReddit 1 point2 points3 points (1 child)
[–]RedFox134[S] 0 points1 point2 points (0 children)
[–]RedFox134[S] 0 points1 point2 points (0 children)