有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在数组中迭代并跳过一些?

例如,我的Java程序中有一个数组:

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

我想写for循环,循环遍历数组,每2个和3个字母,将它们存储在数组中的两个连续索引中,跳过第4个,取5个和6个字母,将它们存储在数组中的两个连续索引中,跳过第7个,并继续为未知大小的数组执行此操作

所以最后一个数组是nums2 = {"b", "c", "e", "f", "h", "i"...}


共 (6) 个答案

  1. # 1 楼答案

    请永远分享你迄今为止的尝试。人们会更愿意帮助你。否则,你最应该得到的就是伪代码。试试这样:

        for (1 to length)
        {
            if( i % 3 != 0)
            add to new array
        }
    
  2. # 2 楼答案

    它运行并打印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));
        }
    }
    
  3. # 3 楼答案

     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个元素、第13个元素,这些元素对应的索引值是3的倍数,我们将根据if条件跳过这些索引元素

  4. # 4 楼答案

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

    如上所述的示例java代码

  5. # 5 楼答案

    可以在for循环中使用if语句,该语句将从数组中的第二项开始,每三个字母跳过一次

    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++;
        }
    }
    
  6. # 6 楼答案

    要获得最简洁的方式,请使用Java 9 streams:

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