# Figuring out for????

• 07-21-2011, 05:20 PM
seanfmglobal
Figuring out for????
I only seem to be replacing the first position of the array when doing this?
I'm used to using the other for loop (the one below)
Code:

```for(int index = 0; index < array.length; index++)     code here```

Code:

```Random ran = new Random();             int[] numbers = new int[8];             numbers[0]=0;             numbers[1]=0;             numbers[2]=0;             numbers[3]=0;             numbers[4]=0;             numbers[5]=0;             numbers[6]=0;             numbers[7]=0;                                     for(int i : numbers){                     numbers[i] = ran.nextInt(30)+1;                //This is the problem right here!!!!             }                                                                       for(int i : numbers)                     System.out.println(i);                                 }```
But printing all elements in the array seems to be working flawlessly....

i've used
Code:

`i = ran.nextInt(30);`
Which doesn't change the value of any element
&
Code:

`numbers[i] = ran.nextInt(30);`
Which changes the value of only the first element

• 07-21-2011, 05:29 PM
KevinWorkman
You're using the "enhanced for loop" incorrectly. It simply gives you what's already in the array, you can't use it to change the primitive values. It doesn't give you the index, it gives you the value. And since every value is zero, and you're using that to set the value at that index, you're only setting the first value.
• 07-21-2011, 09:29 PM
kalyankasyapcse
use the logic....

int j=0;

for(int i : numbers)
{
• 07-21-2011, 09:30 PM
kalyankasyapcse
int j=0;

for(int i : numbers)
{
numbers[j] = ran.nextInt(30)+1;
j++;
}

here u can change the index .....
• 07-21-2011, 09:47 PM
sunde887
Quote:

Originally Posted by kalyankasyapcse
int j=0;

for(int i : numbers)
{
numbers[j] = ran.nextInt(30)+1;
j++;
}

here u can change the index .....

The above is bad advice; if you want to do that(have access to the indices along the way), don't use an enhanced for loop; but instead use a regular loop. You also want to be careful when making modifications in an enhanced for loop, you may just run into "ConcurrentModificationException", which is caused by fail fast iterators; which the enhanced for uses.

Code:

```for(int j=0;j<arr.length;++j){   //make changes }```
Is the way to go.

Also, it's unnecessary to initialize each element individiaully to 0; Just declare the array, then loop through and fill it with values.