gpt4 book ai didi

java - 从文本文件中返回随机行

转载 作者:行者123 更新时间:2023-11-30 11:11:38 25 4
gpt4 key购买 nike

我想制作一个 Mad Libs 程序,您可以在其中编写一个 mad 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 函数来选择要使用的行?

最佳答案

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

例子:

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

关于java - 从文本文件中返回随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com