繁体   English   中英

来自file.txt的随机行

[英]Random line from a file.txt

为什么我的随机选择不起作用? 我输入的所有内容都是从头到尾的堆积线。我认为这将是一个小错误,但我无法弄清楚:/

package pl.mtgpackgenerator;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;

public class Test {
public static void main(String[] args) throws IOException {

    Random random = new Random();
    int randomInt = random.nextInt(59);
    FileReader fr = new FileReader("Common.txt");
    BufferedReader reader2 = new BufferedReader(fr);
    String line = reader2.readLine();

    for (int i = 0; i <= 10; i++) {
          line = reader2.readLine();
          System.out.println(line);
        }
    reader2.close();
    }
}

我们需要使用randomInt来检查行号,并且仅打印该行(如果存在)(以下示例)。 在上面的代码中,randomInt不在任何地方使用。

int index = 0;
while( (line = br.readLine() ) != null) {
    if(index++ == randomInt){
        System.out.println(line);
        break;
    }
}

好吧,它正在寻找我,因为您明确地从文件中读取了前10行,并且您没有使用随机数。

例如,您可以将所有行逐一读取到StringsArrayList中,然后使用randomInt将行打印为randomInt号。 就像arraylist.get(randomInt)一样使用它; 如果您将列表命名为arraylist

@gliacomo说,如果您引用代码,请执行以下操作:

public static void main(String[] args) throws IOException {

    Random random = new Random();
    int randomInt = random.nextInt(59);
    FileReader fr = new FileReader("Common.txt");
    BufferedReader reader2 = new BufferedReader(fr);
    for (int i = randomInt; i <= randomInt + 10; i++) {
        String line = reader2.readLine();
        System.out.println(line);
    }
    reader2.close();
}

在Java 1.8中,您可以这样做

import java.nio.file.Files;
...
Random random = new Random();
int randomInt = random.nextInt(59);
List<String> lines = Files.readAllLines(new File("Common.txt"))
String resultString = lines.get(randomInt);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM