在 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/