Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2012
    Posts
    30
    Rep Power
    0

    Default Adding random number to array list

    I don't understand the list.add(r.nextInt(90) + 10); part. Can someone explain this to me? I recall my professor saying that it has to be minus 1. Basically, 90 + 10 = 100 and 100 -1 = 99 and that's the largest number.
    Java Code:
    //	File:  ArrayListIntro.java   
    
    // Uses an "ArrayList of Integer" object to show list processing basics: 
    // using a for statement to traverse a list, and ArrayList methods add(), 
    // size(), and get(). 
    import java.util.ArrayList;
    import java.util.Random;
    
    /**
     * A class to demonstrate the basics of list processing
     */
    public class ArrayListIntro {
    
        public static void main(String[] args) {
            Random r = new Random();
    
            ArrayList<Integer> list = new ArrayList<Integer>();
            
            // ***** POPULATE the list *****
            
            // add 10 random ints between 10 and 99 to the list
            for (int i = 1; i <= 10; i++) {
                list.add(r.nextInt(90) + 10);
            }
    Last edited by Michael305rodri; 11-13-2012 at 03:59 AM.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,120
    Rep Power
    20

    Default Re: Adding random number to array list

    nextInt() API.
    That's probably a bit too much to read, but the first sentence is the important part:
    "
    Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)...
    "
    So nextInt(10) will provide a number from 0-9, not 0-10.

    In your case nextInt(90) will give you a number from 0-89.
    So adding 10 to that gives you 10-99.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Replies: 5
    Last Post: 10-24-2012, 10:17 PM
  2. Replies: 26
    Last Post: 10-30-2011, 07:01 AM
  3. Adding elements in array list and vectors using threads
    By hina.yousuf@seecs.edu.pk in forum Advanced Java
    Replies: 2
    Last Post: 10-10-2010, 04:07 AM
  4. Replies: 6
    Last Post: 10-03-2010, 09:25 AM
  5. adding list to an array element
    By Preethi in forum New To Java
    Replies: 5
    Last Post: 09-25-2008, 05:23 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •