简体   繁体   中英

Incompatible types: Card cannot be converted to java.lang.String

I keep getting this error with my code. I can't seem to find the problem.

I'm not sure what to do because I even looked in the text book and it gives me a similar method except with different variables.

I'm on BlueJ.

 public int findFirstOfPlayer(String searchString)
{
    int index = 0;
    boolean searching = true;
    while(index < cards.size() && searching) {
        String cardname = cards.get(index); // Error highlights index
        if(cardname.contains(searchString)) {
            searching = false;
        }
        else {
            index++;
        }
        if(searching) {
            return -1;
        }
        else {
            return index;
        }
    }
}

Here is the problem, and if you used something like Eclipse or Idea, it would even highlight it for you.

    String cardname = cards.get(index);

Obviously, cards is not compatible with String, you can't just assign it that way, because your collection card is probably not of type String aka ArrayList<String> cards You can do either:

    String cardname = cards.get(index).toString();

or

    String cardname = String.valueOf(cards.get(index));

Given that Card is a class on its own you can't compare it to string. You have to either implement a method that returns a string you can compare with searchString or use a variable within the card object for the comparisson. Something like this:

String cardname = cards.get(index).toString();

Or

String cardname = cards.get(index).name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM