Reputation: 11
I am very sorry if this is a basic question which has been answered before (I tried looking but I did not find anything)
I am trying to write the following Java method:
String winningCard(String trick, char trump) {
StringBuilder sb = new StringBuilder();
char suit;
char rank;
for(int i = 1; i < trick.length(); i+=2) {
if(trick.charAt(i) == trump) {
suit = trick.charAt(i);
rank = trick.charAt(i-1);
sb.append(rank + suit); //issue here, returns a weird number
break;
}
}
String result = sb.toString();
return result;
}
When called with these arguments "8s7hQd", 'h' for example, it is supposed to return "7h".
If I change the StringBuilder to only append either the suit or the rank, it does it just fine, but if I put it the way it is above it returns "159" which I believe has something to do with the unicode encoding.
I'd very much appreciate if a kind sould could tell me what I am missing.
Thanks in advance
Upvotes: 1
Views: 1057
Reputation: 14738
suit
and rank
are basically numbers. The + is adding these numbers and appending it.
If you place a ""
between, the chars will be appended as you intend, because it forces the compiler to use the + with a String.
sb.append(rank + "" + suit);
Upvotes: 3
Reputation: 140319
+
is a tricksy thing, because it means different things in different contexts.
String
, it acts as the string concatenation operator.You are giving it two char
s: these are numbers, so numeric addition occurs.
Before adding the two chars, they are widened to int
; the result is an int
too. And it is this int
that you are appending to the string builder, hence the "unwanted" number.
So, either avoid using the addition operator at all (best):
sb.append(rank).append(suit);
Or make sure you are using the string concatenation operator:
sb.append("" + rank + suit);
// Left-associative, so evaluated as
// ("" + rank) + suit
sb.append(String.valueOf(rank) + suit);
// Etc.
But actually, you don't need to do either: just append the substring:
sb.append(trick, i-1, i+1);
This extracts a portion of the trick
string, as trick.substring(i-1, i+1)
would, but does it without creating a new string.
And you don't need a loop
Upvotes: 1
Reputation: 126
You can say directly that those chars should be interpreted as String by
sb.append(String.valueOf(rank) + String.valueOf(suit))
Upvotes: 0