2013-02-20 114 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作为另一个海报建议再次启动,否则你自己绑在低效的代码节。

相关问题