java - (随机选择)文件中的名称

标签 java random

我正在尝试制作一个随机名称生成器 方法,该方法将从我存储在两个单独的文本文件中的名称列表中创建随机的名字和姓氏。 (名字.txt && 姓氏.txt)

所以本质上我想从文本文件中选择一个随机标记,并与姓氏文本文件中的随机标记进行匹配:

我只是不确定如何将字符串名称操作为相应的随机整数。

private static void selectName(Scanner firstName, Scanner lastName) {
        // Initialization of Variables
    String randomFirstName = null;
    Random rand = new Random();
    int randomName = rand.nextInt(199) + 1; // 1 - 200

    while (firstName.hasNext()) {
        randomFirstName = firstName.next();
    }

} // closes FileInformation

我能想到的另一个想法是将内容存储到一个数组中并以这种方式横向排列?

这是最好的方法还是有办法像我现在一样做到这一点?

最佳答案

当然有很多方法可以完成任务,我认为,毫无疑问,最好的方法是将所有名称加载到数组或列表中,然后根据随机数索引到该列表中。

List<String> firstnames = new ArrayList<String>();
List<String lastnames = new ArrayList<String>();
//TODO: populate your lists from the appropriate files
Random rand = new Random();
//The advantage to using a list is that you can choose a random based on the actual
//count of names and avoid any out of bounds conditions.
int firstIndex = rand.nextInt(firstnames.size());
int lastIndex = rand.nextInt(lastnames.size());
//Then you index into the list
String randomfirst = firstnames.get(firstIndex);
String randomlast = lastnames.get(lastIndex);

关于java - (随机选择)文件中的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56676044/

相关文章:

java - 如何在Struts Action 类中使用DataSource?它给出了编译错误 "Type mismatch"

c# - 平均特定数字的随机数

java - 如何获得具有线性分布的随机日期?

在非 Activity 类中引用 String 时出现 java.lang.NullPointerException,即使在传入 Context 时也是如此

java - 在 Java 中使用继承或接口(interface)的案例?

java - Hadoop 新 API 的 Class Cast 异常

c - srand()——为什么只调用一次?

c++ - 给定种子和偏移量生成下一个伪随机值

algorithm - 如何控制随机选择的概率?

java - 检查两个 boolean 值是否相等的优雅方法,但要注意 False==null?