简体   繁体   中英

How to place value at random locations in an array using Math.random?

i have an array called Events.

String[] Events = new String[20];

How can I write a method to place 10 random events into this array using math.random() only? My attempt to solving the question is this: I'm new and still learning moving from python to java, stress much.

public static void AddRandomEvents(Events[] event) {
    for(int i = 0; i < event.length; i++){
        int rand = (int) (Math.random() + 10) + 1;
        System.out.println(event[rand]);
    }
}

I had a class called events and thats why its Events[]

Any help or contribution would be helpful. Thanks.

Also adding, I'm placing 10 random events from this array

String[] names = {"Wedding", "Birthday", "Funeral","Clubbing","Anniversary", "Volunteer", "Job fair"};

to the events array, how to? thanks

java.util.Random also offers methods to generate numbers which are pseudorandom, uniformly distributed values. In order to pick 10 random events out of the event array, nextInt(int n) method can be helpful.

    public static void addRandomEvents(Events[] events) {
        Random random = new Random();
        for(int i = 0; i < 10; i++){
            int randomEventIndex = random.nextInt(eventNames.length);
            String randomEventName = eventNames[randomEventIndex];
            String randomEventTime = new Date().toString();
            int randomPriority = random.nextInt(events.length);
            Events randomEvent = new Events(randomEventTime, randomEventName, randomPriority);
            events[i] = randomEvent;
        }
    }

This method can be invoked in this manner:

    static String[] eventNames = {"Wedding", "Birthday", "Funeral","Clubbing","Anniversary", "Volunteer", "Job fair"};
    Events[] events = new Events[10];
    addRandomEvents(events);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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