1

I'm trying to make a method that a random line from lol.txt (which has 113 lines) would be chosen and sent out as message box. How it should work:

  1. Generates random number from 0 till 112
  2. a for loop should go over the random number of lines
  3. output the randomly generated line as a message box

In my case step 2 doesn't work so I was hoping that someone could suggest on that. Here's the code:

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

If you want to send me the solution with an array list that's fine but I would really like it to be how I planned it initially.

4

2 回答 2

5

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

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);
于 2013-07-25T01:25:04.777 回答
2

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

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

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

于 2013-07-25T01:17:40.090 回答