2013-07-25 256 views
1

我试图制作一个方法,从lol.txt(它有113行)的随机行将被选中并作为消息框发送出去。它应如何工作:从文件中随机选择一行

  1. 生成从0至112
  2. for循环应该通过随机数线的
  3. 输出的随机生成的线作为消息框

随机数在我的情况下,第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); 
    } 
} 

如果你想送我一个数组列表,这很好解决,但我想它是真的很喜欢我如何计划它最初。

+0

你可以显示一些你得到的输出吗?每次都是一样的吗?谢谢。 –

+0

你从文件中只读一行;第一个。你如何期待它的工作? –

+0

你不需要'扫描仪'。删除它,代码将更好地工作。 – andy256

回答

2

你只读第一行,这就是为什么你只得到第一行。试试这个..

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

你在做什么是阅读从文件中的一行,使用该行创建一个新的Scanner与循环的每个迭代,然后读它放回line

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);