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

时间:2014-10-30 01:46:50

标签: java arraylist

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

到目前为止,代码是:

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);
    }
}

3 个答案:

答案 0 :(得分:3)

假设每个单词都在它自己的行上,你应该更喜欢读取文件......

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());

但你可以轻松地遍历dictionary并使用相同的想法

(nb-我已经使用了局部变量,所以你要么想让它们成为类字段,要么将它们包装成某种&#34;指标&#34;类 - 你的选择)

答案 1 :(得分:0)

设置一个两个计数器和一个变量,用于保存在使用while循环读入之前找到的当前最长单词。要找到平均值,每次读取一行时,一个计数器会增加一个,并且第二个计数器会累计每个单词中的总字符数(显然,输入的字符总数除以读取的字总数 - - 由总行数表示 - 是每个单词的平均长度。

对于最长的单词,将最长的单词设置为空字符串或将某个虚拟值设置为单个字符。每次读取一行时,将当前单词与先前找到的最长单词进行比较(使用字符串上的.length()方法查找其长度),如果更长时间设置了一个新的最长单词

此外,如果您在文件中包含所有这些内容,我会使用buffered reader来读取您的输入数据

答案 2 :(得分:0)

可能会有所帮助

    String words  = "Rookie never dissappoints, dont trust any Rookie";
         // read your file to string if you get string while reading then you can use below code to do that.

    String ss[] = words.split(" ");

        List<String> list = Arrays.asList(ss);

        Map<Integer,String> set = new Hashtable<Integer,String>();

        int i =0;
        for(String str : list)
        {
            set.put(str.length(), str);
            System.out.println(list.get(i));
            i++;
        }


        Set<Integer> keys = set.keySet();

        System.out.println(keys);
        System.out.println(set);

        Object j[]= keys.toArray();

        Arrays.sort(j);

        Object max = j[j.length-1];

        set.get(max);

        System.out.println("Tha longest word is "+set.get(max));
        System.out.println("Length is  "+max);
相关问题