从文本文件中返回一个随机行

时间:2014-12-05 22:33:17

标签: java string java.util.scanner

我想创建一个Mad Libs程序,你编写一个疯狂的libs模板,然后计算机为你填空。到目前为止,我已经得到了这个:

package madlibs;
import java.io.*;
import java.util.Scanner;

/**
 *
 * @author Tim
 */
public class Madlibs {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    File nouns = new File("nounList.txt");
    Scanner scan = new Scanner(nouns);
    while(scan.hasNextLine()){
        if("__(N)".equals(scan.nextLine().trim())){
            int word = (int) (Math.random() * 100);

        }
    }
}

}

nounList.txt文件包含名词列表,每个名词都在一个单独的行上。问题是:如何使用Math.random函数选择使用哪一行?

3 个答案:

答案 0 :(得分:1)

获取列表中的所有名词,然后从列表中选择一个随机元素。

示例:

// Nouns would contain the list of nouns from the txt file
List<String> nouns = new ArrayList<>();
Random r = new Random();
String randomNoun = nouns.get(r.nextInt(0, nouns.length));

答案 1 :(得分:0)

我会按照我看到的其中一条评论建议采取另一种方法:

try {
        //I would prefer to read my file using NIO, which is faster
        Path pathToMyTextFile = Paths.get("nounList.txt");
        //Then I would like to obtain the lines in Array, also I could have them available for process later
        List<String> linesInFile = Files.readAllLines(pathToMyTextFile, StandardCharsets.ISO_8859_1);
        //If I want to access a random element, I would use random methods to access a random index of the list and retrieve that element
        Random randomUtil = new Random();

        //I will use the formula for random and define the maximum (which will be the length of the array -1) and the minimum which will be zero
        //since the indexes are represented from 0 to length - 1
        int max = linesInFile.size() - 1;
        int min = 0;

        //You can simplify this formula later, I'm just putting the whole thing
        int randomIndexForWord = randomUtil.nextInt((max - min + 1)) + min;

        //Here I get a random Noun
        String randomWord = linesInFile.get(randomIndexForWord);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

这将是另一种方法,无需在每次需要名词时访问它。

问候和......快乐的编码:)

答案 2 :(得分:0)

有两个主要任务:

阅读所有名词

    // Open the file
    File file = new File("MyFile.txt");

    // Attach a scanner to the file
    Scanner fin = new Scanner(file);

    // Read the nouns from the file
    ArrayList<String> nouns = new ArrayList<>();
    while (fin.hasNext()) {
        nouns.add(fin.next());
    }

随机选择一个

    // Pick one at random
    int randomIndex = (int)(Math.random() * nouns.size());
    String randomNoun = nouns.get(randomIndex);

    // Output the result
    System.out.println(randomNoun);

例如,如果我们有10个名词,那么Math.random() * 10会产生0.0到9.999 ... 9的范围。转换为int会截断小数,在0到9之间保持相等的分布。

请注意,您可以从技术上推出一个完美的10.0,程序会因IndexOutOfBoundsException而崩溃。这在统计上是不可能的,但是众所周知,在统计上不可能在代码中不够好。考虑添加逻辑来处理滚动10.0的情况。