2013-02-20 113 views
0

我試圖創建一個程序,它將通過文件數組進行搜索並將唯一文件名存儲到新的文件數組中並返回該新的數組,並且僅將重複項放入一次(如果有的話)。我的代碼運行通過,但不會將值存儲到我創建的新文件陣列中,該陣列沒有設置長度。當我調用它時,它只返回一個空數組。我設置它的方式是檢查是否有任何重複,如果是,則存儲重複一次,如果不存在,則只存儲該值並繼續。問題在於,一旦它通過for循環運行,它就不會存儲這些值。有沒有更好的方法將值存儲在文件數組中?如何將文件數組值存儲到另一個文件數組

這是我的方法uniqueFile從我的測試器塊接收文件陣列。

public static File[] getUnique(File[] files) { 
    int count = 0, place = 0; 
    File[] newFile = new File[] {}; 
    for (int i = 0; i < files.length; i++) { 
     count = 0; 
     for (int x = 1; x < files.length; x++) { 
      if (files[i].equals(files[x])) 
       count++; 
     } 
     try { 
      if (count >= 1) 
       newFile[place] = files[i]; 
      else 
       newFile[place] = files[i]; 
     } catch (Exception e) { 

     } 
     place++; 
    } 

    return newFile; 
} 

這是我的測試塊:

{ 
    File Freckle = new File("Freckle"); 
    File Pickle = new File("Pickle"); 
    File Sam = new File("Sam"); 
    File Cat = new File("Cat"); 
    File[] files = new File[] { Freckle, Pickle, Freckle, Sam, Cat, 
      Pickle }; 

    File[] output = ArrayExercises.getUnique(files); 
    System.out.println(Arrays.toString(output)); 
} 

我把通用文件名進行測試,看看它是否會工作。最終我會合並實際的文件,但是我想在繼續之前先弄清楚這個bug。

+0

爲什麼不使用Set 代替? – Perception 2013-02-20 06:39:47

+0

在Java中使用小寫字母表示變量名是個好習慣,例如'freckle',而不是'Freckle'。這有助於其他讀者區分變量名稱和大寫的類別。 – 2013-02-20 06:42:56

回答

3

你讓事情變得很困難。讓Java爲你做所有的工作。嘗試使用LinkedHashSet,因爲它給你唯一性,並且保留了插入順序。比起每個價值與其他價值的比較,它也會更有效率。

File [] input = {Freckle, Pickle, Freckle, Sam, Cat, Pickle}; 
Set<File> tmp = new LinkedHashSet<File>(); 
for (File each : input) { 
    tmp.add(each); 
} 
File [] unique = new File[tmp.size()]; 
int i = 0; 
for (File each : tmp) { 
    unique[i++] = each; 
} 
System.out.println(Arrays.toString(unique)); 
0

正如其他人所說的那樣,您應該使用Java Collections API,它使生活變得如此簡單。但是讓我們暫時說一下你想讓你的解決方案發揮作用。

他的問題是你的新陣列是零長度,在這裏你有一個非常奇怪的一段代碼。

 if (count >= 1) 
      newFile[place] = files[i]; 
     else 
      newFile[place] = files[i]; 

測試沒有意義,你做的事情完全一樣,不管count的值如何。將非重複字符串添加到陣列時,還需要增加place。 try/catch也是毫無意義的。捕獲一個通用的異常是一個糟糕的做法。

你在哪裏更像下面,但即使這樣做贏了;噸確實希望你想要s儘管該陣列現在只包含唯一的條目,它不像以前一樣長。

public static File[] getUnique(File[] files) { 
    place = 0; 
    File[] newFile = new File[files.size()]; //you were creating an empty array. 
    for (int i = 0; i < files.length; i++) { 
     boolean duplicate = false; // not interested in ho many dupes, just if there is one. 
     for (int x = 1; x < files.length; x++) { 
      if (files[i].equals(files[x])) { 
       duplicate = true; 
       break; // no point in checking the rest. 
      } 
     } 
     // why on earth did you have a try catch? 
     if (!duplicate) { 
      newFile[place++] = files[i]; 
     } 

    } 

    return newFile; 
} 

你需要做的真的什麼是拋出這個路程,使用類似的LinkedHashMap作爲另一個海報建議再次啓動,否則你自己綁在低效的代碼節。

相關問題