如何使用java中增强的for循环计算2D字符串数组中的字符总数?

xkrw2x1b  于 2023-01-15  发布在  Java
关注(0)|答案(3)|浏览(136)
public class LoopPractice {
    public static void main(String[] args) {
        String[][] wordData = {{"study", "consider", "examine", "learn"}, {"ponder", "read", "think", "cogigate"}};
        
        // Below is the question. Am trying to print the total number of characters in the wordData String array.

        //Use nested enhanced for loops to calculate the total number of characters in the wordData 2D array and print the result to the console. (Get the string .length() of each element)

//下面是我所拥有的,但它一直在控制台中打印characterCount为0和每个单词字符的总数。//我不知道如何使用增强的for循环来获取嵌套String数组的String.length()。

int characterCount = 0;
    for(String[] characters: wordData) {
      for(String totalNumber : characters) {
       System.out.println(totalNumber.length();
       }
    }
        System.out.println(characterCount);
        

    }
    
}
z6psavjg

z6psavjg1#

虽然代码正确地遍历了2D数组,但实际上并没有增加总字符数。
只需更改以下行:

System.out.println(totalNumber.length();

致:

characterCount+= totalNumber.length();
aemubtdh

aemubtdh2#

你的想法是正确的,只是不是在嵌套的for循环中打印到控制台,而是需要将字符串的长度添加到characterCount中。因此,你可以这样做:

characterCount = characterCount + totalNumber.length();

或者简称

characterCount += totalNumber.length();

你可以写得更清楚一点:

int count = 0;

for (String[] arr: wordData) {
    for (String str: arr) {
        count += str.length();
    }
}

System.out.println(count);
s4n0splo

s4n0splo3#

整数字符计数= 0;
对于(字符串[] wordRow:字数据){enter code here(字符串字:字行){enter code here字符计数+=字长度();}}
系统输出打印输入(字符计数);

相关问题