0

I need to make a program that populates an array with randoms numbers between 25 and 80 then uses another for loop to print the results on a new line each time. I'm not sure why I get some output and then errors in this code.

    int[] myIntArray = new int [20];
    Random r = new Random();

    for (int i = 0; i <= 20; i++){
        int rand = r.nextInt(80 - 25) + 25;
        myIntArray[i] = rand;
    }

    for (int i = 0; i <= 20; i++){
        System.out.println(myIntArray[i]);
    }
alexs434
  • 19
  • 2

2 Answers2

1

please your array has a size of 20 but you are putting 21 element into it so try this instead

int[] myIntArray = new int [21];
    Random r = new Random();

    for (int i = 0; i <= 20; i++){
        int rand = r.nextInt(80 - 25) + 25;
        myIntArray[i] = rand;
    }

    for (int i = 0; i <= 20; i++){
        System.out.println(myIntArray[i]);
    }
suulisin
  • 1,414
  • 1
  • 10
  • 17
  • Another way to handle it would be to use `i < myIntArray.Length` instead of `i <= 20`. This will allow for different sized arrays. – joncloud May 03 '16 at 00:26
0

You should show the error message in your question :) The index of an array in Java starts at 0, so the highest index in an array of size 20 is 19. You're going out of bounds. Use < not <= when iterating over an array manually.

    int[] myIntArray = new int[20];
    Random r = new Random();

    for (int i = 0; i < myIntArray.length; i++) {
        int rand = r.nextInt(80 - 25) + 25;
        myIntArray[i] = rand;
    }

    for (int i = 0; i < myIntArray.length; i++) {
        System.out.println(myIntArray[i]);
    }
Tibrogargan
  • 4,508
  • 3
  • 19
  • 38