1

我正在尝试计算数组中的字母总数?我试图将数组更改为字符串,然后计算总字符串长度(下面的代码)但不能让它工作?(粗体的兴趣点)提前感谢任何人。

package practical5;

import java.util.Arrays;

public class Part1_9 {

public static void main(String[] args) {

    // declaring and populating array
    String quoteArray[] = { "\"Continuous", "effort", "not", "strength",
            "nor", "intelligence", "is", "the", "key", "to", "unlocking",
            "our", "potential.\"\n" };

    // for loop to print full array
    for (int counter = 0; counter < quoteArray.length; counter++) {
        System.out.print(quoteArray[counter] + " ");
    }// end of for loop

    // Printing array using Enhanced for/ for each loop (Different way to
    // print array)
    for (String element : quoteArray) {
        System.out.print(element + " ");
    }// end of enhanced for

    // line break
    System.out.println();

    // printing number of words in array
    System.out.println("Number of words in array: " + quoteArray.length);

    **// printing total number of letters in array**
    for (int counter = 0; counter < quoteArray.length; counter++) {
        String letters = new String(quoteArray[counter]);
    }

    // printing the smallest word

    // printing the biggest word

}// end of main

}// end of class
4

6 回答 6

2

计算字符串中字母的数量将包含如下代码:

for (int i = 0; i < s.length(); i++)
    if (Character.isLetter(s.charAt(i)))
        // something

s字符串 在哪里。charAt返回i字符串的第 ' 个字符(第一个字符是charAt(0)),并Character.isLetter测试该字符是否为字母。我会让你弄清楚如何使用它以及你可能想要用于什么s

于 2013-11-13T00:53:52.223 回答
1

抱歉,我想我现在已经解决了: 1. 使用 int(在这种情况下称为总计)来保持每个元素中的字母总数。2.使用 arrayName[counter].length 获取每个元素的长度。3. 用户 counter++ 遍历每个元素,直到数组结束。

// printing total number of letters in array
        for (int counter = 0; counter < quoteArray.length; counter++) {
             total +=quoteArray[counter].length();
        }

            System.out.println("Total length of array is: " + total);
于 2013-11-13T00:29:39.523 回答
0

这是粗略的代码,没有运行:

获取字符串数组

对于数组中的每个值 count += string length [i]

taht 将计算数组中每个字符串的每个字符。

为了在数组中找到最小的字符串,只需跟踪每个字符串的长度,然后比较它们,这是一种基本的搜索算法。

于 2013-11-13T00:25:38.737 回答
0

quoteArray.length will only give you the number of elements in the array (in your case the output would be 13).

To get the length of all the strings combined, create a length variable and add to it as you iterate through each array element. Use .length() to get the length of each element and add it to the total length:

int totalLength = 0;
for(String element : quoteArray){
    totalLength+=element.length();
}
System.out.println("The total length of the quote is: " + totalLength);
于 2013-11-13T00:30:15.783 回答
0
int totalCount = 0;
for(String s : quoteArray) {
    totalCount += s.length();
}
于 2013-11-13T00:23:27.997 回答
0

为了

打印数组中的字母总数

查看 java.lang.Character

于 2013-11-13T00:41:58.333 回答