用 Java 编写 LSH 程序,在第一部分中,我阅读了 5 个不同的文本文件并提取了所有独特的单词。然后创建了 5 种不同的单词洗牌方式。现在,我想出的代码显然可以工作,但我知道每当您多次复制粘贴相同的代码块时,您通常可以使用循环来更干净地完成它。在这种情况下,我只是不知道该怎么做。我觉得按照我的方式去做是不好的做法,所以将来我很想避免这种情况。有人能帮我弄清楚如何循环 Java 变量名吗? (或一些类似的复制/粘贴代码块的修复,如下所示)
更新:我需要能够稍后在程序中访问每个唯一打乱顺序的列表,因此我不能简单地将其放入迭代 5 次覆盖前一个列表的 for 循环中。
我也不需要输出列表,这只是为了测试随机播放,抱歉,不清楚。我更新了我的评论。
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
}
最佳答案
public static void main(String[] args) throws FileNotFoundException {
HashSet<String> words = new HashSet<String>();
File dir = new File("filestxt");
for (File f : dir.listFiles()) {
Scanner in = new Scanner(f);
while(in.hasNextLine()) {
words.add(in.nextLine());
}//end while
}//end for
//Create 5 different shufflings of the words
for (int i = 0; i < 5; i++) {
List<String> shuffle = new ArrayList<String>();
for (String s : words) {
shuffle.add(s);
}//end for
Collections.shuffle(shuffle);
System.out.println(shuffle);
}
}
编辑:如果您想稍后访问它,请在进入循环之前声明一个变量
//Create 5 different shufflings of the words
List<ArrayList<String>> listOlists = new ArrayList<ArrayList<String>>();
for (int i = 0; i < 5; i++) {
ArrayList<String> shuffle = new ArrayList<String>();
for (String s : words) {
shuffle.add(s);
}//end for
Collections.shuffle(shuffle);
listOlists.add(shuffle);
System.out.println(shuffle);
}
//access it later
for (List<String> arrayList : listOlists) {
System.out.println(arrayList);
}
关于java - 我怎样才能把它变成一个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22035176/