Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can someone help me understand the simple thing I am forgetting here to get my S

ID: 3850285 • Letter: C

Question

Can someone help me understand the simple thing I am forgetting here to get my StringTester.java program to see my overrided method compare(String, String) to be found?

I know I am missing something simple but I can not put my finger on it.

Here is my code:

import java.util.Comparator;

public class StringLengthComparator implements Comparator<String> {

    @Override
    public int compare(String first, String second) {
        int firstLength = first.length();
        int secondLength = second.length();

        if (firstLength > secondLength) {
            return 1;
        }

        if (secondLength > firstLength) {
            return -1;
        }

        if (secondLength == firstLength) {
            first.compareToIgnoreCase(second);
        }

        return 1;

    }

}

-------------------------------------------------------------------------------------------------------------------------

public class StringTester {

    public static void main(String[] args) {

        String string1 = "james";
        String string2 = "jam";

        int compareInt =0;
        compareInt = compare(string1, string2);
      

    }
}

Explanation / Answer

Hi Buddy,
This is your StringTester Class
public class StringTester {

    public static void main(String[] args) {

        String string1 = "james";
        String string2 = "jam";

        int compareInt =0;
        compareInt = compare(string1, string2);
      

    }
}
you made a call to the compare method from main method in StringTester class. But your compare method is not in the StringTester class. It's in StringLengthComparator class. So you MUST make a call to the compare method using StringLengthComparator object only. So your StringTester class should look like this

class StringTester {

    public static void main(String[] args) {

        String string1 = "james";
        String string2 = "jam";

        int compareInt =0;
        StringLengthComparator comp = new StringLengthComparator();
        compareInt = comp.compare(string1, string2);
      

    }
}

Now you can access the compare method in the StringTester class using the comp variable.

** If your compare method is in the StringTester class and the method is static, you wouldn't need to create an object to access the method. You can call the method like you did in your code.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote