2014-10-30 109 views
0

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

'Math.max'是一个开始,'串#length'可能会帮助 – MadProgrammer 2014-10-30 01:49:01

+1

那是什么嵌套的循环是干什么的,和哪些呢'fileName.length()'必须与你需要读取的字符串数量有关? – dasblinkenlight 2014-10-30 01:50:04

+3

你的循环是完全错误的... – MadProgrammer 2014-10-30 01:50:05

回答

2

假设每个字是在它自己的线,你应该读取文件更像......

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-我使用的局部变量,所以你要么需要,使其类字段或归还包裹在某种“度量”类的 - 你的选择)

+0

这对我进入上下文有很大的帮助!谢谢 – c0der 2014-10-30 03:10:12

+0

很高兴帮助;) – MadProgrammer 2014-10-30 03:11:25

0

设置一个两个计数器和一个变量,该变量保存当前最长的单词,然后开始使用while循环读入。为了找到平均值,每次读取行时都会将一个计数器加1,并让第二个计数器将每个字中的字符总数相加(显然是输入的字符总数除以读取的总字数 - - 由行总数表示 - 是每个单词的平均长度

至于最长的单词,请将最长的单词设置为空字符串或某个虚拟值,如单个字符。读一行比较当前单词与以前找到的最长单词(使用字符串上的.length()方法查找其长度),并且如果其长度设置为新发现的最长单词

此外,如果您将所有这些文件,我会用buffered reader在输入数据读取

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