Question

I have about a one year experience programming Java, I made a static method located in the main class, and for some reason, whenever I compile it gives me an error saying that the compareTo() method from the String class can't be found.

Here's the method:

 public static void displaySpecificResort(String resortName, Resort[] resortList)  
  {
     int low = 0;
     int high = resortList.length - 1;
     int mid;
     while (low <= high)
     {
        mid = low + (high - low);
        if (resortList[mid].compareTo(resortName)<0) 
           low = mid + 1;
        else if (resortList[mid].compareTo(resortName)>0) 
           high = mid - 1;      
        else resortList[mid].display(); 
     }
     if(resortList[mid].getName().compareTo(resortName)!= 0)
        System.out.println("Resort could not be found.");
  }

Here's the error it gives me when I try and compile:

ResortOrganizer.java:157: error: cannot find symbol
        if (resortList[mid].compareTo(resortName)<0) 
                           ^

symbol: method compareTo(String) location: class Resort

ResortOrganizer.java:159: error: cannot find symbol
        else if (resortList[mid].compareTo(resortName)>0) 
                                ^

symbol: method compareTo(String) location: class Resort

2 errors

Can someone explain why it does this? I have a feeling I'm forgetting something important.

Était-ce utile?

La solution

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0) 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top