2013-03-05 171 views
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 

回答

1

因为你只更新0,2和第4个数组的索引。作为iIndex一次两次的循环进行更新。如果您要更新每个值一次如果语句
原始阵列

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

更新阵列

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

删除

iIndex=iIndex+1; 

+0

哇很多活动在这个问题上 - 人编辑/以疯狂的速度:) +1回答为ASCII艺术突出的问题! – 2013-03-05 05:43:44

+1

@SunilD。每个人都想要一块容易的蛋糕:P。 – xyz 2013-03-05 05:44:34

3

因为您选择仅更换索引0 2和4中的原始数组中和离开1和3不变(iIndex加2每次循环迭代)

1

在第一个循环:

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

您增加到iIndex两次。我已经在上面做了笔记。

摆脱第二个,因为您已经将iIndex增加为for循环定义的一部分。

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值替换。

+0

请详细说明您的答案! – swiftBoy 2013-03-05 05:57:03

+0

@RDC详细阐述。谢谢。 – 2013-03-05 06:08:48

2

由于增量已经做了两次:

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

iIndex=iIndex+1; 
/*You are manually incrementing iIndex*/ 
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 
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]); 
      } 
    } 
相关问题