So I have an array of strings and need to take the amount of characters in each string and add them together to get 1 total. How would I go about doing this?
Here is the array:
public class Final21 {
   public static String getLongString(String[] array) {
      String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
   }
}
I am not adding indexes, but the amount of characters in each string. Example: bob has 3 characters, tomtomjack has 10 characters, if you add them it would be 13
Attempts:
       public static int countAllLetters(String[] array) {
      String[] names = {"bob", "maxwell", "charley", "tomtomjack"};                
         int sum = 0;
         for(String s : array)
            sum += s.length();
               return sum;
      int amountOfLetters = countAllLetters(names);
         System.out.println(amountOfLetters);
   }
Gives error:
Final21.java:62: error: unreachable statement
      int amountOfLetters = countAllLetters(names);
          ^
Final21.java:65: error: missing return statement
   }
   ^
2 errors
                Using the stream API, it can be done as follows:
 int sum = Arrays.stream(names)
                .mapToInt(String::length)
                .sum();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With