logo Practice-It logo

longer

Language/Type: Java arrays
Author: Marty Stepp (on 2010/12/28)

Write a method named longer that accepts two arrays of strings a1 and a2 as parameters and returns a new array a3 such that each element of a3 at each index i stores whichever string has greater length (more characters) between the elements at that same index i in arrays a1 and a2. If there is a tie, take the element from a1.

For example, if a1 and a2 store the following elements:

String[] a1 = {"star", "pie", "jelly bean", "car"};
String[] a2 = {"cookie", "fig", "banana", "soda"};

Then your method should return the new array {"cookie", "pie", "jelly bean", "soda"}.

If the arrays a1 and a2 are not the same length, the result returned by your method should have as many elements as the larger of the two arrays. If a given index i is in bounds of a1 but not a2 (or vice versa), there are not two elements to compare, so your result array's element at index i should store the value "oops". For example, if a1 and a2 store the following elements:

String[] a1 = {"Splinter", "Leo", "April", "Don", "Raph"};
String[] a2 = {"Krang", "Shredder", "Bebop"};

Then your method should return the new array {"Splinter", "Shredder", "April", "oops", "oops"}.

For full credit, do not modify the elements of a1 or a2. Do not make any assumptions about the length of a1 or a2 or the length of the strings. You may assume that neither array is null and no element of either array is null.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.