2017-09-26 73 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);