随机行从文件中选择

时间:2013-07-25 01:09:57

标签: java file random line

我正在尝试制作一个方法,选择lol.txt(有113行)的随机行并将其作为消息框发送出去。它应该如何运作:

  1. 生成0到112之间的随机数
  2. for循环应该超过随机行数
  3. 将随机生成的行输出为消息框
  4. 在我的情况下,第2步不起作用,所以我希望有人可以提出建议。这是代码:

    public void close(){
        try{
            Random random = new Random();
            int randomInt = random.nextInt(112);
            FileReader fr = new FileReader("lol.txt");
            BufferedReader reader = new BufferedReader(fr);
            String line = reader.readLine();
            Scanner scan = null;
            for (int i = 0; i < randomInt + 1; i++) {
                scan = new Scanner(line);
                line = scan.nextLine();
            }
            JOptionPane.showMessageDialog(null,line);
        }catch (IOException e){
            JOptionPane.showMessageDialog(null,e.getMessage()+" for lol.txt","File Error",JOptionPane.ERROR_MESSAGE);
        }
    }
    

    如果你想向我发送一个包含数组列表的解决方案,但我真的希望它是我最初的计划方式。

2 个答案:

答案 0 :(得分:4)

最好为此目的使用列表,并使随机大小动态调整为文件大小。如果您想添加更多行而无需更改代码。

BufferedReader reader = new BufferedReader(new FileReader("lol.txt"));
String line = reader.readLine();
List<String> lines = new ArrayList<String>();
while (line != null) {
     lines.add(line);
     line = reader.readLine();
}
Random r = new Random();
String randomLine = lines.get(r.nextInt(lines.size()));
JOptionPane.showMessageDialog(null,randomLine);

答案 1 :(得分:2)

您只阅读第一行,这就是您只获得第一行的原因。试试这个..

String line = reader.readLine();
for (int i = 0; i < randomInt + 1; i++) {
  line = reader.readLine();
}

您正在做的是从文件中读取一行,使用该行在每次循环迭代时创建一个新的Scanner,然后将其读回line

相关问题