在Java中编写一个LSH程序,在第一部分中,我阅读了5个不同的文本文件,并提取了所有的独特单词。然后创建了5个不同的洗牌词。现在,我提供的代码很明显,但是我知道,无论何时您复制粘贴相同的代码块很多次,您通常可以使用循环完成它更干净。在这种情况下,我只是不知道如何。我觉得像我这样做是不好的习惯,所以在将来我很乐意避免这种情况。有人能帮我弄清楚如何循环Java变量名吗? (或类似的复制/粘贴代码块的一些类似的修复)我怎样才能把它变成一个循环?
更新:我需要能够访问我的程序中后来每个独特的洗牌列表,所以我不能简单地把它放在for循环迭代5次覆盖先前的列表。
我也不需要输出列表,这只是测试洗牌,对不起,不清楚。我更新了我的评论。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class LSH {
public static void main(String[] args) throws FileNotFoundException {
//Find all unique words in the Files in dir /filestxt
HashSet words = new HashSet();
File dir = new File("filestxt");
for (File f : dir.listFiles()) {
Scanner in = new Scanner(f);
while(in.hasNextLine()) {
String line = in.nextLine();
words.add(line);
}//end while
}//end for
//Create 5 different shufflings of the words
LinkedList shuffle1 = new LinkedList();
LinkedList shuffle2 = new LinkedList();
LinkedList shuffle3 = new LinkedList();
LinkedList shuffle4 = new LinkedList();
LinkedList shuffle5 = new LinkedList();
for (Object s : words) {
shuffle1.add(s.toString());
}//end for
for (Object s : words) {
shuffle2.add(s.toString());
}//end for
for (Object s : words) {
shuffle3.add(s.toString());
}//end for
for (Object s : words) {
shuffle4.add(s.toString());
}//end for
for (Object s : words) {
shuffle5.add(s.toString());
}//end for
Collections.shuffle(shuffle1);
Collections.shuffle(shuffle2);
Collections.shuffle(shuffle3);
Collections.shuffle(shuffle4);
Collections.shuffle(shuffle5);
//This block for testing purposes only
System.out.println(shuffle1);
System.out.println(shuffle2);
System.out.println(shuffle3);
System.out.println(shuffle4);
System.out.println(shuffle5);
}//end main
}
为什么你'Set's和'List's原料,而不是通用的? – fge
因为这是我第二年的Java,我很容易懒惰。请记住,未来不要使用原始类型,除非这样做具有特定的优势。谢谢! –