Answer:
public static int[] listLengthOfAllWords(String [] wordArray){
int[] intArray = new int[wordArray.length];
for (int i=0; i<intArray.length; i++){
int lenOfWord = wordArray[i].length();
intArray[i]=lenOfWord;
}
return intArray;
}
Explanation:
- Declare the method to return an array of ints and accept an array of string as a parameter
- within the method declare an array of integers with same length as the string array received as a parameter.
- Iterate using for loop over the array of string and extract the length of each word using this statement int lenOfWord = wordArray[i].length();
- Assign the length of each word in the String array to the new Integer array with this statement intArray[i]=lenOfWord;
- Return the Integer Array
A Complete Java program with a call to the method is given below
<em>import java.util.Arrays;</em>
<em>import java.util.Scanner;</em>
<em>public class ANot {</em>
<em> public static void main(String[] args) {</em>
<em> String []wordArray = {"John", "James", "David", "Peter", "Davidson"};</em>
<em> System.out.println(Arrays.toString(listLengthOfAllWords(wordArray)));</em>
<em> }</em>
<em> public static int[] listLengthOfAllWords(String [] wordArray){</em>
<em> int[] intArray = new int[wordArray.length];</em>
<em> for (int i=0; i<wordArray.length; i++){</em>
<em> int lenOfWord = wordArray[i].length();</em>
<em> intArray[i]=lenOfWord;</em>
<em> }</em>
<em> return intArray;</em>
<em> }</em>
<em>}</em>
This program gives the following array as output: [4, 5, 5, 5, 8]