Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add character amounts in an array?

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
like image 397
CaptainMuffenz Avatar asked Dec 24 '22 07:12

CaptainMuffenz


1 Answers

Using the stream API, it can be done as follows:

 int sum = Arrays.stream(names)
                .mapToInt(String::length)
                .sum();
like image 159
Ousmane D. Avatar answered Jan 08 '23 09:01

Ousmane D.