为什么这个代码的输出是这样的?

时间:2013-03-05 05:34:55

标签: java

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

7 个答案:

答案 0 :(得分:3)

因为你只替换了原始数组中的索引0 2和4,并且保持1和3不变(iIndex每次循环迭代增加2)

答案 1 :(得分:2)

因为增量已经完成两次:

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

 iIndex=iIndex+1; 
 /*You are manually incrementing iIndex*/

答案 2 :(得分:2)

Dude,因为当你开始你的第一个循环时,它会改变索引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

答案 3 :(得分:1)

因为您只更新数组的第0和第4个索引。如果对于语句
iIndex在循环中一次更新两次 原始数组

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

更新了数组

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

删除

iIndex=iIndex+1;  

如果您想更新每个值。

答案 4 :(得分:1)

在你的第一个循环中:

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

您添加iIndex两次。我上面做了笔记。

删除第二个,因为你已经将iIndex作为for循环定义的一部分递增。

答案 5 :(得分:0)

请注意这一行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.
     } 

上述循环将从0开始,每次增加2,如上所述。因此,iIndex值将为0,2,4 ...。索引1,3处的值保持不变,值为0,2,4 ......将被iIndex值替换。

答案 6 :(得分: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]); 
             } 
     }
相关问题