0
class MainDemo{ 

     public static void main(String args[]){ 
        float arrayOne[] = {1, 2, 3, 4,5}; 
        for(int iIndex=0; iIndex<arrayOne.length; iIndex++) 
        { 
               arrayOne[iIndex] = iIndex; 
               iIndex=iIndex+1; 
         } 
         for(int iIndex=0; iIndex<arrayOne.length; iIndex++) 
         { 
               System.out.println(arrayOne[iIndex]); 
         } 
 } 
}


为什么是输出?

0.0
2.0
2.0
4.0
4.0

代替

0.0
1.0
2.0
3.0
4.0
4

7 回答 7

3

because youre only replacing indexes 0 2 and 4 in the original array and leaving 1 and 3 untouched (iIndex is incremented by 2 each loop iteration)

于 2013-03-05T05:37:43.560 回答
2

因为增量已经完成了两次:

 for(int iIndex=0; iIndex<arrayOne.length; iIndex++)  
 /* Forloop itself increments iIndex*/

 iIndex=iIndex+1; 
 /*You are manually incrementing iIndex*/
于 2013-03-05T05:39:46.233 回答
2

伙计,因为当您开始第一个循环时,它会更改索引 0,2 和 4 的值,其先前的值分别为 1,3 和 5,并且对于这些索引,循环后的新值分别为 0,2 和 4,这就是您得到输出

0.0
2.0
2.0
4.0
4.0

代替

1.0
2.0
3.0
4.0
5.0
于 2013-03-05T05:54:59.077 回答
1

Because you are updating only 0,2 and 4th index of array. As iIndex is updated twice once in loop in once if for statement
Original array

float arrayOne[] = {1, 2, 3, 4,5};  

Updated array

   float arrayOne[] = {0, 2, 2, 4,4};
                       |_____|____|______ Are updated 

Remove

iIndex=iIndex+1;  

If you want to update every value.

于 2013-03-05T05:37:27.097 回答
1

In your first loop:

for(int iIndex=0; iIndex<arrayOne.length; iIndex++) //<-- here
{ 
      arrayOne[iIndex] = iIndex; 
      iIndex=iIndex+1; //<-- here - get rid of this
} 

You add to iIndex twice. I've made notes above.

Get rid of the second one as you already increment iIndex as part of your for loop definition.

于 2013-03-05T05:37:51.643 回答
0

Beacuse of this line iIndex=iIndex+1; .

for(int iIndex=0; iIndex<arrayOne.length; iIndex++) //iIndex get incremented by 1 here.
    { 
           arrayOne[iIndex] = iIndex; 
           iIndex=iIndex+1; //iIndex get incremented by 1 here.
     } 

The above loop will start from 0 and get incremented by 2 each time as mentioned above. So iIndex values will be 0,2,4... .Value at index 1,3... remains unchanged and values at 0,2,4... get replaced by iIndex value.

于 2013-03-05T05:38:52.170 回答
0
public static void main(String args[]){ 
            float arrayOne[] = {1, 2, 3, 4,5}; 
            for(int iIndex=0; iIndex<arrayOne.length; iIndex++) 
            { 
                   arrayOne[iIndex] = iIndex; 
                  // iIndex=iIndex+1; comment this line, twice increment is not required. 
             } 
             for(int iIndex=0; iIndex<arrayOne.length; iIndex++) 
             { 
                   System.out.println(arrayOne[iIndex]); 
             } 
     }
于 2013-03-05T05:57:42.720 回答