开发者

Enum print question in Java

开发者 https://www.devze.com 2023-02-27 00:59 出处:网络
I declared an enum Card which has a getValue method that returns an int representation with for every Card (clubs, hearts, etc.). I observed that I am unable to use the + operator in the following sta

I declared an enum Card which has a getValue method that returns an int representation with for every Card (clubs, hearts, etc.). I observed that I am unable to use the + operator in the following statement becau开发者_Go百科se the compiler thinks I am performing an add operation with two incompatible types.

Why doesn't the compiler automatically overload here? The only way I can display this is if I stuff a "" in between so currentCard + "" + currentCard.getValue() is accepted. Is there anyway to get around this?

for(Card currentCard: Card.values())  
    System.out.println(currentCard+ currentCard.getValue());


The issue you are running into is simply that the plus operator only does String concatenation when there is a String as one of the items being added together. There is nothing that makes it assume String just because it's inside a println.

That's why once you throw an empty string in there, it then sees this as String concatenation and concatenates the string representation of each item together. Otherwise you are adding an object of type Card to an int.

So solve it, simply do this:

System.out.println(currentCard.toString() + currentCard.getValue());


you have to convince the java compiler you are working with strings, there's no way the compiler can figure that out automatically when looking at an enum and an int. personally, i would use:

"" + currentCard + currentCard.getValue()


You can override toString(), as suggested in the Card example seen here. Then all you need is this:

 System.out.println(currentCard);
0

精彩评论

暂无评论...
验证码 换一张
取 消