Java 确保没有两条随机线是相同的。
下面的代码非常适合从文件中随机选取行。我如何确保不出现两行,因为random可能会再次重复同一行Java 确保没有两条随机线是相同的。,java,Java,下面的代码非常适合从文件中随机选取行。我如何确保不出现两行,因为random可能会再次重复同一行 BufferedReader reader = new BufferedReader(new FileReader(file)); List<String> lines = new ArrayList<String>(); String line = reader.readLine(); while( line != null ) { lines.add(line)
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++;
}
BufferedReader=newbufferedreader(newfilereader(file));
列表行=新的ArrayList();
字符串行=reader.readLine();
while(行!=null){
行。添加(行);
line=reader.readLine();
}
随机r=新随机();
int i=0;
而(i<4){
System.out.println(lines.get(r.nextInt(lines.size()));
i++;
}
简单:使用集合
跟踪您已经使用的行。在这里,我添加了一个检查,以确保文件中有足够的行来避免无限循环
// 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++;
}
}
//要打印的行数
最终整型打印计数=4;
//检查以确保文件中实际有4行
if(lines.size()
注意:一般来说,您希望缩小变量的范围。因此,我将
while
-循环转换为For
-循环,并且在找到唯一行号时仅递增I
简单:使用集合
跟踪您已经使用的行。在这里,我添加了一个检查,以确保文件中有足够的行来避免无限循环
// 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++;
}
}
//要打印的行数
最终整型打印计数=4;
//检查以确保文件中实际有4行
if(lines.size()
注意:一般来说,您希望缩小变量的范围。因此,我将
while
-循环转换为For
-循环,并且在找到唯一行号时仅递增I
除非您的文件有什么特别之处,否则您所能做的就是在每次添加新行之前,遍历所有行并进行检查。运行过程中获得的行越多,此过程将变得越慢。如果行已在集合中,则将行添加到集合中,然后再递增。或者,读任意四行,然后随机化。@ElliottFrisch聪明的主意!非常感谢您,如果您的文件没有什么特别之处,您所能做的就是在添加新行之前,遍历所有行并检查每一次。运行过程中获得的行越多,此过程将变得越慢。如果行已在集合中,则将行添加到集合中,然后再递增。或者,读任意四行,然后随机化。@ElliottFrisch聪明的主意!非常感谢你非常感谢你。。。非常感谢你。。。感激