java - ArrayList:获取最长字符串的长度,获取字符串的平均长度

标签 java arraylist

在 Java 中,我有一个方法可以读取一个文本文件,该文件包含字典中的所有单词,每个单词都在自己的行上。 它使用 for 循环读取每一行并将每个单词添加到 ArrayList 中。 我想获取数组中最长单词(字符串)的长度。另外,我想获取字典文件中最长单词的长度。将其分成几个方法可能会更容易,但我不知道语法。

到目前为止,代码是:

public class spellCheck {
static ArrayList <String> dictionary; //the dictonary file


/**
 * load file
 * @param fileName the file containing the dictionary
 * @throws FileNotFoundException 
 */
public static void loadDictionary(String fileName) throws FileNotFoundException {
Scanner in = new Scanner(new File(fileName));

while (in.hasNext())
{

    for(int i = 0; i < fileName.length(); ++i)
    {
        String dictionaryword = in.nextLine();
        dictionary.add(dictionaryword);
    }
}

最佳答案

假设每个单词都在自己的行上,您应该更像......

try (Scanner in = new Scanner(new File(fileName))) {

    while (in.hasNextLine()) {
        String dictionaryword = in.nextLine();
        dictionary.add(dictionaryword);        
    }

}

请记住,如果您打开资源,您就有责任关闭资源。请参阅The try-with-resources Statement了解更多详情...

计算指标可以在读取文件后完成,但既然你在这里,你可以做类似的事情......

int totalWordLength = 0;
String longest = "";
while (in.hasNextLine()) {
    String dictionaryword = in.nextLine();
    totalWordLength += dictionaryword.length();
    dictionary.add(dictionaryword);        
    if (dictionaryword.length() > longest.length()) {
        longest = dictionaryword;
    }
}

int averageLength = Math.round(totalWordLength / (float)dictionary.size());

但是您可以轻松地循环遍历字典并使用相同的想法

(注意-我使用了局部变量,因此您要么想要将它们设为类字段,要么将它们返回到某种“指标”类中 - 您的选择)

关于java - ArrayList:获取最长字符串的长度,获取字符串的平均长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26643702/

相关文章:

java - 从接口(interface) I 的列表中创建类 C 的 ArrayList

java - 从字符串中删除字符

ArrayList 的 Java While 循环不会终止

java - EditText 中的表情符号

java - 在 ConcurrentHashMap 上进行的操作是线程安全的吗?

java - 了解java.nio包中的 channel

java - 当在 Eclipse 中停止 Android 模拟器时,是否清除所有缓存,或者 Eclipse 是否为下一个模拟器存储它?

c - C 中的 Arraylist 不工作

java - 将 ArrayList 元素组收集到另一个 ArrayList

java - 成员对象调用类方法