0

I am trying to make program that create an ArrayList of initial size of 1 and populate it with random numbers. Next, the ArrayList is cleared and the size of ArrayList is increased by 1 and again filled with random numbers. I want my program to repeat those steps until the ArrayList size will be equal to number specified by user.

So the output will be for example like:

1

3,8

6,3,7

...

n

I have produced so far:

public static void main (String args[]){
    
    ArrayList<Integer> al = new ArrayList<Integer>(); 
    Random rand = new Random();
    int val=1;
    int ii =1;
    while(val<400){
    for (int j = 0; j<ii;)
    {
        ii++;
        val++;
        pick = rand.nextInt(100);
        al.add(pick);
    }

    System.out.println("Contents of al: " + al);

    al.clear();
    System.out.print("Array has been cleared: " + al);
}

Any ideas how to make it work?

1
  • 1
    You have an infinite for loop (j is always =0 and ii is always >=0) hence your list grows out of bounds. You should rethink your loops. Commented Feb 13, 2015 at 18:28

2 Answers 2

1

You never increment j. You are incrementing ii and val inside the for loop where as I think you actually want to do it in the while loop. Try the example below.

    ArrayList<Integer> al = new ArrayList<Integer>(); 
    Random rand = new Random();
    int val=1;
    int ii =0;
    while(val < 400){
        for (int j = 0; j<ii; j++) {
            int pick = rand.nextInt(100);
            al.add(pick);
        }
        ii++;
        val++;
        System.out.println("Contents of al: " + al);
        al.clear();
        System.out.print("Array has been cleared: " + al);
    }

Your task would be much easier if you gave your variables meaningful names. e.g.

    ArrayList<Integer> al = new ArrayList<Integer>(); 
    Random rand = new Random();
    int lineNumber = 1;
    int lineLength = 0;
    while(lineNumber < 400){
        for (int randCount = 0; randCount < lineLength; randCount++) {
            int pick = rand.nextInt(100);
            al.add(pick);
        }
        lineLength++;
        lineNumber++;
        System.out.println("Contents of al: " + al);
        al.clear();
        System.out.print("Array has been cleared: " + al);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank your for your answer bhspencer. I was messing around with this code for a while. Thank you again.
0
for (int j = 0; j<ii;) {
    ii++;
    val++;
    pick = rand.nextInt(100);
    al.add(pick);
}

is an infinite loop(j is always 0 and ii is always positive). You should fix it(according to the desired semantics).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.