This code is supposed to find the nth short word

For example, if you are passed an array containing the words

"Mary", "had", "a", "little", "lamb"

and you are asked to return the second word, you would return

"a"

Below is my attempt to solve this but im pretty confused and dont know what im doing.

Any help would be greatly appreciated. thanks

public class Words
{
   /**
      Returns the nth short word (length <= 3) in an array.
      @param words an array of strings
      @param n an integer > 0
      @return the nth short word in words, or the empty string if there is
      no such word
   */
	
   public String nthShortWord(String[] words, int n)
   {
	 
	   
	   String tempWord = "";
	   if(words.length <=3)
	   {
		   for (int i = 0; i < words.length; i++)
		   {
			   return tempWord;   
		   }
	   }
	   
	   else if(n > words.length)
	   {
		   return "";
	   }
	return tempWord;
   }
}

Recommended Answers

All 3 Replies

if(words.length <=3)

This is wrong here, the length attribute would give you the length og the array, so for example if you have 5 words in the array, words.length will give you 5. Whereas you have to calculate the lenght of each word in the array.
Here's how you can go about it :
1. Write a for loop that traverses the array till the end of it.
2. for every word within the array check it's lenght in characters by using the length method of the String class, since every element in the array is a String, you can do this with

if (words[i].length()>3){
    wordCnt++;
    if(wordCnt==n){
        shortWord=words[i];
        break;//increment the counter towards n, check it after incrementing, if it is equal to 'n', this is the word you need. Else continue.
    }
}

3. This way you would either reach to the nth short word or the end of teh array, in the former case break from the loop with the nth short word assigned to shortWord in the latter case return a blank/empty string.

For example, if you are passed an array containing the words

"Mary", "had", "a", "little", "lamb"

and you are asked to return the second word, you would return

"a"

actually, if you want the second word, you would get "had", since that is the second element. what you mean is, return the element with index 2.

String words[] = {"Mary", "had", "a", "little", "lamb"};
return words[2];

@stultuske :
No actually he wants to return the nth short word, where short word is a word with less than or equal to three characters. I too got confused with it, but when I saw the code posted by him I got the logic he was trying to explain.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.