2015-03-24 54 views
0

我使用螞蟻來取代一個URL值:循環6次,但打印的9倍,而不是3

<property name="dir" value="dir1, dir2, dir3" /> 
<property name="files" values="file1, file2, file3" /> 

我想在像DIR1組合替換URL值,則文件1 DIR2 ,file2然後dir3,file3。我循環兩次取代,而不是打印三次,並更換所有的值,它的替換和打印6次。

這裏是我的代碼:

<target name="test"> 
<foreach param="dirval" in="${dir}"> 
<foreach param="filesval" in="${files}"> 
<sequential> 
<echo message="Testing structure: ${dirval}/${filesval}" /> 
</sequential> 
</foreach> 
</foreach> 

輸出預計:

Testing structure: dir1/file1 
Testing structure: dir2/file2 
Testing structure: dir3/file3 

不過的了:

Testing structure: dir1/file1 
Testing structure: dir1/file2 
Testing structure: dir1/file3  
Testing structure: dir2/file1 
Testing structure: dir2/file2 
Testing structure: dir2/file3 
Testing structure: dir3/file1 
Testing structure: dir3/file2 
Testing structure: dir3/file3 

回答

1

的你有這個輸出的原因是你在一個雙重foreach循環中有3個元素,所以你循環和打印結果9次而不是所需的3次。 (foreach循環在dir中,3次* foreach循環遍歷文件,3次)(正如你可以在你當前的輸出中看到的那樣)

我不知道Ant,但是在Java中你試圖完成的東西看起來像這個。 (爲了得到所期望的結構,或輸出)

僅使用一個循環:

string dir[] = {"dir1","dir2","dir3"}; 
string files[] = {"file1","file2","file3"}; 

for (int i = 0; i < dir.length, i++){ 
    System.out.println("Testing structure: " + dir[i] + "/" + file[i]) 
} 
+0

嗯,我不知道如何用Java做的,但我在這裏找一個螞蟻的專家,因爲他們可能知道這個問題並且知道得更好 – fscore 2015-03-25 13:25:58

0

下面的代碼使用第三方Ant-Contrib library。螞蟻的Contrib提供了幾個任務,使我們能夠模仿數組:

<project name="ant-foreach-array" default="run"> 
    <!-- Ant-Contrib provides <var>, <for>, <math>, and <propertycopy>. --> 
    <taskdef resource="net/sf/antcontrib/antlib.xml" /> 

    <target name="run"> 
     <property name="dirs" value="dir1,dir2,dir3" /> 
     <property name="files" value="file1,file2,file3" /> 

     <var name="fileIndex" value="1" /> 
     <for list="${files}" delimiter="," param="file"> 
      <sequential> 
       <property name="file.${fileIndex}" value="@{file}" /> 
       <math 
        result="fileIndex" datatype="int" 
        operand1="${fileIndex}" operation="+" operand2="1" 
       /> 
      </sequential> 
     </for> 

     <var name="dirIndex" value="1" /> 
     <for list="${dirs}" delimiter="," param="dir"> 
      <sequential> 
       <propertycopy 
        name="fileIndex" 
        from="file.${dirIndex}" 
        override="true" 
       /> 
       <echo message="Testing structure: @{dir}/${fileIndex}" /> 
       <math 
        result="dirIndex" datatype="int" 
        operand1="${dirIndex}" operation="+" operand2="1" 
       /> 
      </sequential> 
     </for> 
    </target> 
</project> 

結果:

run: 
    [echo] Testing structure: dir1/file1 
    [echo] Testing structure: dir2/file2 
    [echo] Testing structure: dir3/file3