1

I am trying to finish my assignment, but I am not sure how to complete it. I have 3 arrays in my code, each of which have first names and last names (the last name comes before the first one in the arrays).

Which function should I use in order to decided whether a string is before the other? I was thinking compare, but I'm not too sure how to implement it.

This is my code so far:

public static void main(String[] args)
{

    String[] section1 = {"Curie, Marie", "Feynman, Richard", "Germain, Sophie",
            "Turing, Alan"};
    String[] section2 = {"Bolt, Usain", "Graf, Steffi","Hamm, Mia"};
    String[] section3 = {"Bach, Johann Sebastian", "Beethoven, Ludwig van",
            "Mozart, Wolfgang Amadeus", "Schumann, Clara"};

    String[] merged = mergeSortedArrays(section1, section2);
    String[] merged = mergeSortedArrays(merged, section3);

    for(int i = 0; i < merged.length(); i ++)
        System.out.print(merged[i]);



    }


 //Do not change the method header
public static String[] mergeSortedArrays(String[] a1, String[] a2)
{

    int i = 0, j = 0, k = 0;
    while(a1[i] != null && a2[j] != null)
    {
        if(a1[i] "comes before" a2[j])
        {
            merged[k] = a1[i];
            i++;
            else {
                merged[k] = a2[j];
                j++;
            }
            k++;
        }
        return merged;



    }

}
0

1 Answer 1

1

To compare two strings, use

if(a1[i].compareTo(a2[j]) <= 0)  {   //Means: a1[i] <= a2[j]     
   System.out.println("a1[" + i + "] (" + a1[i] + ") is less-than-or-equal-to a2[" + i + "] (" + a2[i] + "));
}

Or

if(a1[i].compareTo(a2[j]) < 0)  {   //Means: a1[i] < a2[j]     
   System.out.println("a1[" + i + "] (" + a1[i] + ") is less than a2[" + i + "] (" + a2[i] + "));
}

I recommend the comments as I've done, because I find looking at the compareTo function very confusing. I have to keep reminding myself that the operator is sort of "in place" of the compareTo. I always comment it like this.

I've noticed some serious issues with your code, unrelated to string comparison:

  • Your else has no close curly-brace before it.
  • The object merged is never declared in the mergeSortedArrays function
  • Your while loop needs to check that the array indexes are not too high given the arrays, or you're going to get an ArrayIndexOutOfBoundsException
  • anArray.length() is incorrect. Eliminate the parentheses.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.