Skyemelia
Skyemelia

Reputation: 3

How to set the value of multiple elements in an array in java "after" instantiating?

I'm making a game and want to throw some randomness into the generation, as such I need to set the value of all the elements in an array after making the array.

The best I can come up with so far is doing this 1 by 1 for each element, but I would like to do it all at once if possible.

Example of what I'm looking for:

int[] array = new int[5];
//"randomNo is set as a random number between 1 and 5 inclusive."
switch(randomNo){
    case 1: array = {0, 1, 2, 3, 4}; break;
    case 2: array = {8, 9, 10, 11, 12}; break;
    case 3: array = {3, 4, 5, 6, 7}; break;
    case 4: array = {18, 19, 20, 21, 22}; break;
    case 5: array = {14, 15, 16, 17, 18}; break;
}

As such I can't just set the values at the start, but don't want to go 1 by 1 like so:

case 1: array[0] = 8; array[1] = 9;  array[2] = 10;  array[3] = 11;  array[4] = 12; break;

Upvotes: 0

Views: 102

Answers (3)

Jesper
Jesper

Reputation: 206876

Do the creation and initialization at the same time inside the switch, like this:

int[] array;
//"randomNo is set as a random number between 1 and 5 inclusive."
switch(randomNo){
    case 1: array = new int[]{0, 1, 2, 3, 4}; break;
    case 2: array = new int[]{8, 9, 10, 11, 12}; break;
    case 3: array = new int[]{3, 4, 5, 6, 7}; break;
    case 4: array = new int[]{18, 19, 20, 21, 22}; break;
    case 5: array = new int[]{14, 15, 16, 17, 18}; break;
    default: array = new int[5]; break;
}

Upvotes: 3

Sam Mullinix
Sam Mullinix

Reputation: 306

You can loop through the array and set each value to a random number. This example will do that for each value in array and assign a number between 1 and 50.

for(int i = 0; i< array.length; i++){
    Random rand = new Random();
    array[i] = rand.nextInt(50) + 1;
}

Upvotes: 1

codeman51
codeman51

Reputation: 156

Instead of hand-picking the random numbers (which isn't very random) let the Random library do the work for you:

  import java.util.Random;

  Random rand = new Random();
  for (int i = 0; i < array.length; i++) {
     array[i] = rand.nextInt();`
  }

Upvotes: 1

Related Questions