[java] String method cannot be found in a main class method

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.

This question is related to java string class methods main

The answer is


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)  

Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with string tag:

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript How to change the datetime format in pandas How to write to a CSV line by line? convert string to number node.js "error: assignment to expression with array type error" when I assign a struct field (C) Remove 'b' character do in front of a string literal in Python 3 Ruby: How to convert a string to boolean What does ${} (dollar sign and curly braces) mean in a string in Javascript? How do I make a new line in swift converting json to string in python PHP - remove all non-numeric characters from a string C# - How to convert string to char? How can I remove the last character of a string in python? Converting std::__cxx11::string to std::string How to convert string to date to string in Swift iOS? Convert time.Time to string TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3 How can I capitalize the first letter of each word in a string using JavaScript? Best way to verify string is empty or null Hive cast string to date dd-MM-yyyy Check for special characters in string How to convert any Object to String? Print "\n" or newline characters as part of the output on terminal Set the maximum character length of a UITextField in Swift How do I convert a Python 3 byte-string variable into a regular string? What does $ mean before a string? Delete the last two characters of the String Splitting a string into separate variables Figure out size of UILabel based on String in Swift Matching strings with wildcard How do I concatenate strings? Print very long string completely in pandas dataframe Check string for nil & empty Convert float to string with precision & number of decimal digits specified? How do I print my Java object without getting "SomeType@2f92e0f4"? enum to string in modern C++11 / C++14 / C++17 and future C++20 How should I remove all the leading spaces from a string? - swift Convert array to JSON string in swift Swift extract regex matches Convert a file path to Uri in Android How would I get everything before a : in a string Python

Questions with class tag:

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes? Beginner Python: AttributeError: 'list' object has no attribute Call static methods from regular ES6 class methods How to implement private method in ES6 class with Traceur How do I correctly setup and teardown for my pytest class with tests? Calling one method from another within same class in Python What is the difference between static func and class func in Swift? Why Choose Struct Over Class? What's the difference between integer class and numeric class in R Getting error: ISO C++ forbids declaration of with no type undefined reference to 'vtable for class' constructor ES6 class variable alternatives Private properties in JavaScript ES6 classes c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration) How to create multiple class objects with a loop in python? JavaScript: Create and destroy class instance through class method How to override the properties of a CSS class using another CSS class Best way to style a TextBox in CSS How would I access variables from one class to another? C++ [Error] no matching function for call to How do I get an object's unqualified (short) class name? Call a Class From another class Add and remove a class on click using jQuery? AttributeError: 'datetime' module has no attribute 'strptime' Select distinct using linq class method generates "TypeError: ... got multiple values for keyword argument ..." Abstract Class:-Real Time Example Why is enum class preferred over plain enum? Classes vs. Functions passing object by reference in C++ What does "Could not find or load main class" mean? jQuery select child element by class with unknown path add class with JavaScript How do I resolve ClassNotFoundException? Set Font Color, Font Face and Font Size in PHPExcel C# : Converting Base Class to Child Class Nested or Inner Class in PHP Arrays in type script Tkinter example code for multiple windows, why won't buttons load correctly? How to move div vertically down using CSS Creating a Zoom Effect on an image on hover using CSS?

Questions with methods tag:

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args) Purpose of a constructor in Java? Methods vs Constructors in Java class method generates "TypeError: ... got multiple values for keyword argument ..." Java: Sending Multiple Parameters to Method How to make method call another one in classes? Write a mode method in Java to find the most frequently occurring element in an array PHP call Class method / function What does .class mean in Java? C# cannot convert method to non delegate type Non-Static method cannot be referenced from a static context with methods and variables Can overridden methods differ in return type? How to log as much information as possible for a Java Exception? How to return a boolean method in java? Method to get all files within folder and subfolders that will return a list Python calling method in class Can there exist two main methods in a Java program? Compare two objects with .equals() and == operator method in class cannot be applied to given types Converting Integers to Roman Numerals - Java 'Class' does not contain a definition for 'Method' How to call a parent method from child class in javascript? Return a string method in C# HTTP Status 405 - Request method 'POST' not supported (Spring MVC) Passing just a type as a parameter in C# C# : Passing a Generic Object How to use a variable of one method in another method? C# referencing a variable from another method Verify a method call using Moq Why do some functions have underscores "__" before and after the function name? Python 3 string.join() equivalent? List method to delete last element in list as well as all elements calling a function from class in python - different way How can I create a Java method that accepts a variable number of arguments? Retrieving data from a POST method in ASP.NET Java Inheritance - calling superclass method Set and Get Methods in java? Abstract methods in Java Count words in a string method? How to get an object's methods?

Questions with main tag:

String method cannot be found in a main class method How to access global variables Maven Error: Could not find or load main class Eclipse error "Could not find or load main class" Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args) What does "Could not find or load main class" mean? C# importing class into another class doesn't work In Python, can I call the main() of an imported module? Can there exist two main methods in a Java program? Could not find or load main class with a Jar File Explanation of 'String args[]' and static in 'public static void main(String[] args)' Can't execute jar- file: "no main manifest attribute" int main() vs void main() in C Should I return EXIT_SUCCESS or 0 from main()? What is the Eclipse shortcut for "public static void main(String args[])"? C++ Fatal Error LNK1120: 1 unresolved externals "Error: Main method not found in class MyClass, please define the main method as..." calling another method from the main method in java What is the proper declaration of main in C++? Using Spring 3 autowire in a standalone Java application What is "String args[]"? parameter in main method Java What does if __name__ == "__main__": do? What should main() return in C and C++? Why is the Java main method static?