2015-02-23 39 views
0

該程序的目的是導入2個文件。明文文件和字典明文文件。比較2個數組列表的內容

程序應搜索文件並比較單詞並打印出不匹配的單詞,即拼寫錯誤的單詞。我已經使用掃描儀通讀並將每行放入一個數組(字典是按行列出的),但我無法弄清楚如何比較兩個數組列表之間的對方。

任何幫助表示讚賞。

import java.io.File;  
import java.io.PrintWriter; 
import java.util.Scanner; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 

public class Dictionary { 
public static void main(String[] args) throws FileNotFoundException { 
    ArrayList <String> words = new ArrayList<String>(); 
    ArrayList <String> dict = new ArrayList<String>(); 

    File inputFile = new File(args [0]); 
    File inputDictionary = new File(args [1]); 

    Scanner in = new Scanner(inputFile); 
    Scanner inDict = new Scanner(inputDictionary); 

    while(in.hasNext()) { 
     String word = in.next(); 
     words.add(word);  
    } 

    while (inDict.hasNextLine()) { 
     String correctWord = inDict.nextLine(); 
     dict.add(correctWord); 
    } 
} 
} 
+0

使用循環和'dict.contains' – immibis 2015-02-23 03:47:24

+0

怎麼樣使用Apache的百科全書 - CollectionUtils做:'ArrayList的mispelledWords = CollectionUtils.disjunction(詞,字典);'? – Ascalonian 2015-02-23 04:22:48

回答

0

試試這個。

for(String word : words){ //loop for words 
    if(!dict.contains(word)) //check if dict contain word 
    System.out.println(word); //print it if dict doesnt have word 
} 
0

您需要遍歷單詞Arraylist中的每個單詞並查看它是否包含在dict Arraylist中。

boolean[] misspelled = new boolean[words.size()]; 
int i = 0; 
for (String word : words) { 
    misspelled[i] = !dict.contains(word); 
    i++; 
} 

這定義布爾的陣列,保持所有的拼錯的單詞軌道並且如果在特定索引的單詞不在字典列表內包含的,比該索引處的布爾值被設置爲真,這意味着這個詞不拼寫正確。

0

您需要遍歷兩個ArrayList並對它們進行比較。

for(int i = 0; i<words.size();i++){ 
     for(int j = 0; j<dict.size(); j++){ 
      if(words.get(i).equals(dict.get(j))){ 
       // they are equivalent strings 
      }else{ 
       // not equivalent 
      } 
     } 
    } 
+0

如何使用增強型for循環代替? – Ascalonian 2015-02-23 04:06:59

+0

@Ascalonian也適用。我更喜歡傳統的循環,因爲給了你更多的控制,允許你獲取/更改迭代變量。 – Dando18 2015-02-23 04:08:01