简体   繁体   English

(随机选择)来自文件的名称

[英](Random Selection) Names From A File

I am trying to make a random name generator method that will create a random first and last name from a list of names I have stored in two separate text files. 我正在尝试创建一个随机名称生成器 方法 ,该方法将从我存储在两个单独文本文件中的名称列表中创建一个随机的名字和姓氏。 (First Name.txt && LastName.txt) (First Name.txt && LastName.txt)

So essentially I want to select a random token from the text file and match it from a random token from the last name text file: 所以基本上我想从文本文件中选择一个随机标记,并从姓氏文本文件中的随机标记中匹配它:

I'm just not sure how I can manipulate the string names into a respective random integer. 我只是不确定如何将字符串名称操作为相应的随机整数。

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

The other idea I could think of was to store the contents into an array and transverse that way? 我能想到的另一个想法是将内容存储到数组中并横向移动?

Would that be the best way or is there a way to do it as I have now? 那会是最好的方式,还是有办法像现在这样做?

Of course there are many ways to accomplish the task, I think, hands down, the best way is to load all the names into an array or list, and then just index into that list based on a random number. 当然,有许多方法可以完成这项任务,我认为,最好的方法是将所有名称加载到数组或列表中,然后根据随机数索引到该列表中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM