gpt4 book ai didi

java - 如何使用java从特定行中选择随机文本值

转载 作者:行者123 更新时间:2023-12-02 02:36:36 25 4
gpt4 key购买 nike

我有三个输入字段。

  • 名字
  • 最后一项
  • 出生日期

我想从属性文件中获取每个输入的随机数据。这就是属性文件的样子。字段名称和 = 应被忽略。

 - First Name= Robert, Brian, Shawn, Bay, John, Paul
- Last Name= Jerry, Adam ,Lu , Eric
- Date of Birth= 01/12/12,12/10/12,1/2/17

示例:对于名字:文件应从以下名称中随机选择一个名称

  Robert, Brian, Shawn, Bay, John, Paul

而且我需要忽略之前的任何内容=

FileInputStream objfile = new FileInputStream(System.getProperty("user.dir "+path);
in = new BufferedReader(new InputStreamReader(objfile ));
String line = in.readLine();

while (line != null && !line.trim().isEmpty()) {
String eachRecord[]=line.trim().split(",");
Random rand = new Random();
//I need to pick first name randomly from the file from row 1.
send(firstName,(eachRecord[0]));

最佳答案

如果您知道属性文件中总是只有这 3 行,我会将每行放入一个以索引作为键的 map 中,然后在 map 范围内随机生成一个键。

// your code here to read the file in

HashMap<String, String> firstNameMap = new HashMap<String, String>();
HashMap<String, String> lastNameMap = new HashMap<String, String>();
HashMap<String, String> dobMap = new HashMap<String, String>();

String line;
while (line = in.readLine() != null) {
String[] parts = line.split("=");
if(parts[0].equals("First Name")) {
String[] values = lineParts[1].split(",");
for (int i = 0; i < values.length; ++i) {
firstNameMap.put(i, values[i]);
}
}
else if(parts[0].equals("Last Name")) {
// do the same as FN but for lastnamemap
}
else if(parts[0].equals("Date of Birth") {
// do the same as FN but for dobmap
}
}

// Now you can use the length of the map and a random number to get a value
// first name for instance:
int randomNum = ThreadLocalRandom.current().nextInt(0, firstNameMap.size(0 + 1);
System.out.println("First Name: " + firstNameMap.get(randomNum));

// and you would do the same for the other fields

可以使用一些辅助方法轻松重构代码以使其更清晰,我们将其保留为硬件分配:)

这样您就可以缓存所有值,您可以随时调用并获取随机值。我意识到这不是具有嵌套循环和 3 个不同映射的最佳解决方案,但如果您的输入文件仅包含 3 行并且您不希望有数百万个输入,那么它应该没问题。

关于java - 如何使用java从特定行中选择随机文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46226406/

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