Home > Software engineering >  Sum arrays from arraylist Java
Sum arrays from arraylist Java

Time:03-15

How can i sum arrays from arraylist, i want to get sum of string lenght from arrays and print the sum

the bug is in main

public class Listy {
public static void main(String[] Listy) {

    List<String[]> words = new ArrayList<>();
    words.addAll(Arrays.asList((["Pat"], ["Michał"],))
    System.out.println(getSumOfLenghts(a));




    public static int getSumOfLenghts(List<String[]> words) {
    int sum = 0;

    for (String[] currentarray:words) {
        sum  = currentarray.length;
    }
    return sum;
}

CodePudding user response:

As @shmosel comment, you get the errors because you did not declared a array as java syntax, you have a list of String array:

I edited your code as below and it's work:

public static void main(String[] args) {
    
    List<String[]> words = new ArrayList<>();
    words.add(new String[]{"Pat", "Michal"});
    words.add(new String[]{"Pat 2", "Michal 2"});
    System.out.println(getSumOfLenghts(words));
}
  • Related