2017-09-26 28 views
0

例如,我有這樣的陣列在我的Java程序:如何迭代數組並跳過一些?

String nums[] = {"a", "b", "c", "d", "e", "f", "g", "h" ...} 

我想要寫一個循環,將遍歷數組,並採取每2和第3個字母和他們每個人存儲在兩個連續指數法在數組中,跳過第4個,取第5個和第6個字母,並將每個連續兩個索引存儲在一個數組中,跳過第7個並繼續處理未知大小的數組。

所以最終的陣列將nums2 = {"b", "c", "e", "f", "h", "i"...}

+0

哪種語言? –

+0

正常迭代。只需在循環內添加一個if來查看該值是否被跳過。看起來你會在第一場比賽後的第三場比賽中跳投。所以'if(i%3!= 0)'爲基於0的。 – twain249

+0

歡迎使用堆棧溢出。你有什麼嘗試?請張貼[mcve],向我們展示您的嘗試,以及您錯誤的位置,讓我們真正地幫助您。 – AJNeufeld

回答

0

這將運行並打印out = b, c, e, f, h, i

public class Skip { 
    public static String[] transform(String[] in) { 
     int shortenLength = (in.length/3) + ((in.length % 3 > 0) ? 1 : 0); 
     int newLength = in.length - shortenLength; 
     String[] out = new String[newLength]; 
     int outIndex = 0; 
     for (int i = 0; i < in.length; i++) { 
      if (i % 3 != 0) { 
       out[outIndex++] = in[i]; 
      } 
     } 
     return out; 
    } 

    public static void main(String[] args) { 
     String[] nums = {"a", "b", "c", "d", "e", "f", "g", "h", "i" }; 
     String[] out = transform(nums); 
     System.out.println("out = " + String.join(", ", out)); 
    } 
} 
+0

謝謝你的時間,這太棒了!很高興看到我有類似的東西,現在我知道如何解決它。 – Beatrice

1

你可以的,如果內的語句中使用for循環,將跳過每一個第三個字母從陣列中的第二項開始。

int j=0; //separate counter to add letters to nums2 array 
for(int i=0; i<nums.length; i++) { //starts from 1 to skip the 0 index letter 
    if (i%3 != 0) { //should include every letter except every third 
     nums2[j] = nums[i]; 
     j++; 
    } 
} 
+0

從'i = 1'開始,表達式'(i-1)%3'將立即評估爲'0'。你跳過了第一,第二,第五,第八等等,給出了「c」,「d」,「f」,「g」,「i」,「j」,......這不是什麼被要求。 – AJNeufeld

1
for(int num : nums){ 
    if(num % 3 == 1) Continue; 
    System.out.print(num + " "); 
} 

Java代碼示例,如上

0
String[] array = {"a", "b", "c", "d", "e", "f", "g", "h" ...} //Consider any datatype 
for(int i =1; i<array.length;i++) { 
if(i%3 == 0) { 
} 
else { 
System.out.println(a[array]); 
} 

} 

這樣,它會跳過4元,7元,10元,第十三元素,其對應的指數值是3的倍數,我們跳過由if條件該索引元件..

1

請始終分享您迄今爲止所嘗試的內容。人們會更樂於幫助你。否則,你應得的最多的是僞代碼。嘗試是這樣的:

for (1 to length) 
    { 
     if(i % 3 != 0) 
     add to new array 
    } 
0

對於最簡潔的方式,使用Java 9流:

String[] nums2 = IntStream.range(0, nums.length) 
    .filter(i -> i % 3 != 0) 
    .mapToObj(i -> nums[i]) 
    .toArray(String[]::new);