【问题标题】:Extracting String from a specefic line in a txt file [duplicate]从文本文件中的特定行中提取字符串 [重复]
【发布时间】:2019-12-16 14:25:01
【问题描述】:

我是一个java初学者,我有一个小问题,我希望你们能帮助我。 我有一个包含大量随机名称的 Names.txt 文件,每一行都有一个适当的名称 (解释: 约翰 迈克尔 安东尼 ETC...) 我一直在编写一个随机选择以下名称之一的函数:

public static void RandomNameGenerator() throws FileNotFoundException
{
    // the File.txt has organized names, meaning that each line contains a name
    //the idea here is to get a random int take that number and find a name corresponding to that line number
    int txtnumlines = 0; // how many lines the txt file has
    Random random = new Random();
    Scanner file = new Scanner(new File("Names.txt")); //loads the txt file
    while (file.hasNext()) //counts the number of lines
    {
        file.nextLine();
        txtnumlines += 1;
    }
    int randomintname = random.nextInt(txtnumlines);
    // takes a random number, that number will be used to get the name from the txt line
    String RandomName = "";

    // I'm stuck here :(
}

问题是我不知道如何继续,更具体地说,如何使用代表随机线的随机整数提取该名称(比如说 alex)

希望我的问题很清楚, 谢谢你帮助我!

【问题讨论】:

标签: java


【解决方案1】:

在这里,您可能想试试这个:

public static void RandomNameGenerator() throws FileNotFoundException
{
    // the File.txt has organized names, meaning that each line contains a name
    //the idea here is to get a random int take that number and find a name corresponding to that line number
    int txtnumlines = 0; // how many lines the txt file has
    Random random = new Random();
    Scanner file = new Scanner(new File("Names.txt")); //loads the txt file
    Scanner fileReloaded = new Scanner(new File("Names.txt")); //Let's use another one since we can't reset the first scanner once the lines have been counted (I'm not sure tho)
    while (file.hasNext()) //counts the number of lines
    {
        file.nextLine();
        txtnumlines += 1;
    }
    int randomintname = random.nextInt(txtnumlines);
    // takes a random number, that number will be used to get the name from the txt line

    int i = 0;
    String RandomName = "";
    while(fileReloaded.hasNext())
    {
        String aLine = fileReloaded.nextLine();
        if (i == randomintname) Randomname = aLine;
        i++;
    }

    // Now you can do whatever you want with the Randomname variable. You might want to lowercase the first letter, however. :p
}

【讨论】:

  • 谢谢先生,我厌倦了这样的类似方法,但由于缺乏经验而徒劳无功
【解决方案2】:

读取所有行

String[] lines = new Scanner(
    MyClass.class.getClassLoader().getResourceAsStream("Names.txt"),
    StandardCharsets.UTF_8.name()
).next().split("\\A");

提取随机线

Random random = new Random();
String randomLine = lines[random.nextInt(lines.length)].trim();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-26
    • 2012-03-30
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2019-02-22
    相关资源
    最近更新 更多