VIPIN K.

asked • 04/16/23

Need help figuring out what is wrong with my Java code

Here is the problem that I am working on:


"You should implement the function String findLongestName(String [] names) which takes an array of Strings as an input containing a list of names, and return the String that has the longest name.

To do so, try to follow these steps:

  1. The first step is to calculate and store the length of the input array, this is done using names.length; and store that in an integer variable.
  2. Then create a new String called longestName that will store the longest name in the array of names, initialize it with the first name in the array, that is names[0].
  3. Next, you should create a for loop that will compare every name in the array using names[i] against the longestName. Only replace the longestName value if the names[i] is longer .
  4. Finally, return the longestName variable as the return value of the function."


Here is my attempted solution:


public String findLongestName(String [] names){

int size = names.length;

String longestName = names[0];

int longestNameSize=longestName.length();

for(int i=1; i<size; i++){

if(longestNameSize[i]>longestNameSize){

longestName=names[i];

}

}


return longestName;

}

2 Answers By Expert Tutors

By:

Berg K. answered • 04/16/23

Tutor
New to Wyzant

Reliable, Quality Tutoring Service

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.