在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,我很容易懶惰。請記住,未來不要使用原始類型,除非這樣做具有特定的優勢。謝謝! –