1

I'm trying to create a program to create an array of the numbers 1 through 100 and then randomize them. So far I have this, but don't know what to do next:

public class Random100Array
{
   public static void main(String args[])
   {
      {
      int[] nums = new int[100];
      char current;
      int a;

      for (int i = 0; i <= nums.length; i++) {
         nums[i] = i + 1;
      }

      for (int i1 = 0; i1 <=nums.length; i1++) {
         double random = (Math.random() * 100) + 1;
      }
      }
   }
}

Also, THIS ISN'T HOMEWORK. I am a student and I'm currently on winter break. This program gives me this output for some reason. What am I doing wrong?

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
    at Random100Array.main(Random100Array.java:11)
f3d0r
  • 541
  • 3
  • 12
  • 27
  • Why are you creating a random number `nums.length` times and then not doing anything with it? Also, when you say "randomize them", do you mean shuffle the array or choose a new random number for each element? – murgatroid99 Jan 01 '14 at 21:27
  • do you want to get a permutation of these numbers or just an array of of random numbers from a range? – pkacprzak Jan 01 '14 at 21:35
  • @pkacprzak I want to randomize the numbers in the array using the array that I already created – f3d0r Jan 01 '14 at 21:36

4 Answers4

2

Use < instead of <= in your for loops.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
1

Initializing an array with the length of 100 means, you have indices ranging from 0 to 99, so you won't have index 100, thats why you receive this exception. nums.length will be 100 (since you initialize the length with 100. Basically your for-loop is ranging from 0 to 100 (which are 101 nums) this is out of bound.

Use < instead of <= inside the for loops

for shuffeling the array, try something like this: https://stackoverflow.com/a/1520212/995320

Community
  • 1
  • 1
bbuecherl
  • 1,609
  • 12
  • 20
1

Firstly, you should take care of your for-loops conditions as mentioned in other answers.

Then, for shuffling your input array, you can use this code:

import java.util.Random;

public class Program {

    public static void main(String[] args) 
    {
        int[] nums = new int[100];

        for(int i = 0; i < nums.length; ++i) 
        {
            nums[i] = i + 1;
        }

        Random generator = new Random();
        for(int i = 0; i < nums.length; ++i) 
        {           
            int j = generator.nextInt(nums.length - i);         
            int tmp = nums[nums.length - 1 - i];
            nums[nums.length - 1 - i] = nums[j];
            nums[j] = tmp;
        }
    }

}
pkacprzak
  • 5,537
  • 1
  • 17
  • 37
0

You need to use < and not <=

Also, you can use a try catch to escape the exception, but this would not be considered good practice