How To Randomly Generate From A Given List?

30,906

Solution 1

import java.util.*; 

public class characters 
{
    public static void main(String[] args)
    {
       Random generate = new Random();
       String[] name = {"John", "Marcus", "Susan", "Henry"};

       System.out.println("Customer: " + name[generate.nextInt(4)]);      

    }
}

See how easy it is? I gave 4 simple names which can be replaced with words and such. The "4" in the code represents the number of names in the String. This is about as simple as it gets. And for those who want it even shorter(all I did was decrease the spacing):

import java.util.*; 
public class characters{ 
public static void main(String[] args){
Random generate = new Random(); 
String[] name = {"John", "Marcus", "Susan", "Henry"};
System.out.println("Customer: " + name[generate.nextInt(4)]); }}

Solution 2

You can shuffle the ArrayList and take the first element,or iterate and take all of them in different order.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class NameGenerator {
    public static void main(String[] args) {
        String[] peoples = {"Bob","Jill","Tom","Brandon"};
        List<String> names = Arrays.asList(peoples);
        Collections.shuffle(names);
        for (String name : names) {
            System.out.print(name + " ");
        }
    }
}

Otherwise you can create a random number each time and take a different name.

        int index = new Random().nextInt(names.size());
        String anynames = names.get(index);
        System.out.println("Your random name is" + anynames + "now!");

Solution 3

You can express it in fewer lines:

String[] names = {"Bob", "Jill", "Tom", "Brandon"};
int index = Math.random() * names.length;
String name = names[index];
System.out.println("Your random name is" + name + "now!");

Solution 4

import java.util.*;
import java.io.*;

public class Main {
  public static void main(String[] args) throws Exception {

    // To generate random information
    Random random = new Random(); // necessary for this project

    // To get the names and surnames .txt files in local directory
    Scanner male = new Scanner(
        new File("/storage/emulated/0/Download/male.txt")); // male names .txt

    Scanner female = new Scanner(
        new File("/storage/emulated/0/Download/female.txt")); // female names .txt

    Scanner surname = new Scanner(
        new File("/storage/emulated/0/Download/surnames.txt")); // surname lists .txt


    // Each name and surname will be stored here for easier use
    LinkedList<String> maleNames = new LinkedList<String>(); // male names
    LinkedList<String> femaleNames = new LinkedList<String>(); // female names
    LinkedList<String> surnameLists = new LinkedList<String>(); // surname lists

    // Loops are used to automatically store each name and surname into the list
    while (male.hasNext()) {
        maleNames.add(male.next()); // auto store each male name into the list
    }
    while (female.hasNext()) {
        femaleNames.add(female.next()); // auto store each female name into the list
    }
    while (surname.hasNext()) {
        surnameLists.add(surname.next()); // auto store each surname into the list
    }

    // Sorting Elements is optional
    surnameLists.sort(Comparator.naturalOrder()); // optional
    femaleNames.sort(Comparator.naturalOrder()); // optional
    maleNames.sort(Comparator.naturalOrder()); // optional

    // Closing these objects is necessary
    surname.close(); // necessary
    female.close(); // necessary
    male.close(); // necessary


    // For loop is used to generate multiple information
    for (int index = 0; index < 10000; index++) { // optional

        String firstName = "", lastName = "", completeName = "", gender = ""; // temporary storage

        byte age = (byte)(random.nextInt(99 - 18 + 1) + 18); // generates random age between 18 to 99 years old

        // If boolean value is true, it is male
        if (random.nextBoolean()) {
            firstName += maleNames.get(random.nextInt(maleNames.size())); // generates random name
            lastName += surnameLists.get(random.nextInt(surnameLists.size())); // generates random surname

            firstName = (firstName.substring(0, 1).toUpperCase() + firstName.substring(1)); // uppercase first letter
            lastName = (lastName.substring(0, 1).toUpperCase() + lastName.substring(1)); // uppercase first letter

            completeName = firstName + " " + lastName; // creates a complete name
            gender = "Male"; // sets the gender into male

            // Otherwise, it is female
        } else {
            firstName += femaleNames.get(random.nextInt(femaleNames.size())); // generates random name
            lastName += surnameLists.get(random.nextInt(surnameLists.size())); // generates random surname

            firstName = (firstName.substring(0, 1).toUpperCase() + firstName.substring(1)); // uppercase first letter
            lastName = (lastName.substring(0, 1).toUpperCase() + lastName.substring(1)); // uppercase first letter

            completeName = firstName + " " + lastName; // creates a complete name
            gender = "Female"; // sets the gender into female
        }

        // Finally, printing out the results
        System.out.printf("Name: %s%nAge:  %d%nSex:  %s%n%n", completeName, age, gender);
    }
  }
}
Share:
30,906
Admin
Author by

Admin

Updated on November 21, 2021

Comments

  • Admin
    Admin over 2 years

    The problem I'm running into is to randomly generate names from a specific list. I want my program to be able to only pick from these names: Bob, Jill, Tom, and Brandon. I tried studying arrays but I think that's a bit too far for me to learn yet. So far I think I have a general idea, but I'm not sure.

    import java.util.Random;
    
    public class NameGenerator
    {
    
            public static void main(String[] args)
            {
    
               System.out.println("This is a program that generates random names from a list!");
    
               int Bob = 0;
               int Jill = 0;
               int Tom = 0;
               int Brandon = 0;
               Random r = new Random();
    

    After that I'm kind of stuck on how to get the generator going.

    Update: Well I took your advices and tried learning arrays. So far this is what I have.

    ArrayList<String> names = new ArrayList<String>();
    names.add("Bob");
    names.add("Jill");
    names.add("Tom");
    names.add("Brandon");
    
    char index = randomGenerator.nextChar(names.size());
    String anynames = names.get(index);
    System.out.println("Your random name is" + anynames + "now!");
    

    However now it says randomGenerator cannot be resolved and void methods cannot return a value. Any ideas on where I went wrong?