以下代码非常适合从文件中挑选随机行。如何确保不会出现两行,因为随机可能会再次重复同一行。
BufferedReader reader = new BufferedReader(new FileReader(file));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
while( line != null ) {
lines.add(line);
line = reader.readLine();
}
Random r = new Random();
int i = 0;
while(i < 4){
System.out.println(lines.get(r.nextInt(lines.size())));
i++;
}
答案 0 :(得分:0)
简单:使用Set
跟踪您已使用过的行。在这里,我添加了一个检查,以确保文件中确实有足够的行以避免无限循环。
// Number of lines to print
final int PRINT_COUNT = 4;
// Check to make sure there are actually 4 lines in the file
if(lines.size() < PRINT_COUNT)
throw new IllegalStateException("Too few lines in file. Total lines="+lines.size());
// Declare a set to record which lines were selected
Set<Integer> chosen = new HashSet<>();
Random r = new Random();
for(int i = 0; i < PRINT_COUNT;) {
int nextInt = r.nextInt(lines.size());
if(!chosen.contains(nextInt)){
chosen.add(nextInt);
System.out.println(lines.get(nextInt));
i++;
}
}
注意:作为一般规则,您希望减少变量的范围。出于这个原因,我将while
- 循环转换为for
- 循环,并在找到唯一的行号时仅递增i
。