簡體   English   中英

(隨機選擇)來自文件的名稱

[英](Random Selection) Names From A File

我正在嘗試創建一個隨機名稱生成器 方法 ,該方法將從我存儲在兩個單獨文本文件中的名稱列表中創建一個隨機的名字和姓氏。 (First Name.txt && LastName.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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM