[英]How can I Sum arrays lengths from arraylist Java
我如何从 arraylist 求和 arrays 长度,我想从 arrays 获取字符串长度的总和并打印总和
该错误在主要
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;
}
正如@shmosel 评论,你得到错误是因为你没有将数组声明为 java 语法,你有一个字符串数组列表:
我按如下方式编辑了您的代码,并且可以正常工作:
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));
}
编辑:为了回答您的评论问题,我创建了这个示例,其中包含两个 function:
getSumOfLenghts
this function 返回列表中有多少String
getSumOfEachStringLenghts
this function 返回列表中所有字符串的总和。
public class Listy { 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)); System.out.println(getSumOfEachStringLenghts(words)); } public static int getSumOfLenghts(List<String[]> words) { int sumArrElem = 0; for (String[] currentarray:words) { sumArrElem += currentarray.length; } return sumArrElem; } public static int getSumOfEachStringLenghts(List<String[]> words) { int sumForEachElem = 0; for (String[] currentarray:words) { for (String s: currentarray) { sumForEachElem += s.length(); } } return sumForEachElem; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.