I would like to know what it causing the error of \"bad operand types for binary operator \'>\'\" down below I have the codes for both my Hand and C
getCardFace()
returns a String. <
and >
operators exist only for numeric types.
You can use c1.getCardFace().compareTo(c.getCardFace()) < 0
or c1.getCardFace().compareTo(c.getCardFace()) > 0
instead, to compare the Strings according to their natural ordering.
if ( c1.getCardFace() > c.getCardFace() ||
(c1.getCardFace().equals(c.getCardFace()) && c1.getFaceValue() < c.getFaceValue()) ) {
would become
if ( c1.getCardFace().compareTo(c.getCardFace()) > 0 ||
(c1.getCardFace().equals(c.getCardFace()) && c1.getFaceValue() < c.getFaceValue()) ) {
and
if ( c1.getFaceValue() < c.getFaceValue() ||
(c1.getFaceValue() == c.getFaceValue() && c1.getCardFace() > c.getCardFace()) ) {
would become
if ( c1.getFaceValue() < c.getFaceValue() ||
(c1.getFaceValue() == c.getFaceValue() && c1.getCardFace().compareTo(c.getCardFace()) > 0) ) {
getCardFace()
is returning String value but you can't use < , > , <= or >=
for comparing String.
Don't use these operators <
,>
and ==
to compare two Strings, instead use compareTo
method.
From Javadoc:
public int compareTo(String anotherString)
Compares two strings lexicographically. The comparison is based on the
Unicode
value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal;compareTo
returns0
exactly when theequals(Object)
method would returntrue
.
An example of comparing two Strings
String s1="example1", s2="example2";
if ( s1.compareTo(s2) > 0 )
System.out.println("First string is greater than second.");
else if ( s1.compareTo(s2) < 0 )
System.out.println("First string is smaller than second.");
else
System.out.println("Both strings are equal.");
Note: The compareTo
method is case sensitive i.e "java" and "Java" are two different strings if you use compareTo
method. String "java" is greater than "Java" as ASCII value of 'j' is greater than 'J'. If you wish to compare strings but ignoring the case then use compareToIgnoreCase
method.
public int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences. This method returns an integer whose sign is that of calling
compareTo
with normalized versions of the strings where case differences have been eliminated by callingCharacter.toLowerCase(Character.toUpperCase(character))
on each character.