2014-10-30 143 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);