java - (随机选择)文件中的名称
问题描述
我正在尝试创建一个随机名称生成器 方法,该方法将从我存储在两个单独的文本文件中的名称列表中创建一个随机的名字和姓氏。(名字.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);
推荐阅读
- django - Django 站点:如何更快地使用 Databse 加载站点页面
- c# - C# ChromeDriver 代理未设置
- python - 如何使 True Check Forever
- reactjs - 如何获取rowFields以比较枢轴网格devextreme中的两列反应js
- ios - PDF 与 Swift 的交互
- c++ - 如何在 UI 中编辑/更新 dataGridView 内容并使用 C++ winforms 将它们传递给 SQL 工作台?
- azure - Azure 中默认不加载默认招摇索引页面
- ios - 如何将选定的 tableview 行存储在数组中?
- javascript - 基于文件扩展名的 Javascript 显示图像
- kubernetes - 一组微服务的常用 helm 图表模板