簡體   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