返回一个包含其他所有数字的数组

时间:2014-03-29 01:57:31

标签: java

我试图创建一个以数组作为输入的程序并删除所有奇数索引。它编译但不运行。由于某种原因,它标记了while循环。我也不确定如何解决这个问题。

由于

public class MoreArrayProblems
{
    public int[] everyOther (int [] a){
        if (a.length < 2){
        return a;

        }

        int []l = new int[a.length/2];
        //if (a.length%2==0) {int l[]= new int [a.length/2];}
        //else {l[] = int [a.length + 1 / 2];}

        int loc= 0, i = 1;
        while ( i<a.length){
            l[i] = a[i-1];   //for some reason this doesn't work
            i += 2;

        }

        return l;

    }

}

3 个答案:

答案 0 :(得分:1)

这是您的代码SSCCE,并添加了一个有用的调试语句。

  import  java.util.Arrays;
public class MoreArrayProblems
{
  public static final void main(String[] ignored)  {
     System.out.println(Arrays.toString(
        (new MoreArrayProblems()).everyOther(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})));
  }
    public int[] everyOther (int [] a){
        if (a.length < 2){
        return a;

        }

        int []l = new int[a.length/2];
        //if (a.length%2==0) {int l[]= new int [a.length/2];}
        //else {l[] = int [a.length + 1 / 2];}

        int loc= 0, i = 1;
        while ( i<a.length){
System.out.println("l.length=" + l.length + ", a.length=" + a.length + ", i=" + i + ", [i - 1]=" + (i - 1) + "");
            l[i] = a[i-1];   //for some reason this doesn't work
            i += 2;

        }
        return l;
    }
}

输出:

[C:\java_code\]java MoreArrayProblems
l.length=5, a.length=10, i=1, [i - 1]=0
l.length=5, a.length=10, i=3, [i - 1]=2
l.length=5, a.length=10, i=5, [i - 1]=4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
        at MoreArrayProblems.everyOther(MoreArrayProblems.java:21)
        at MoreArrayProblems.main(MoreArrayProblems.java:5)

数组中的第一个元素索引0,而不是1。这个事实,以及上面的调试输出揭示了一些非常大的问题。

答案 1 :(得分:0)

public class MoreArrayProblems {
    public static void main(String[] args) {
        int divider = 2;
        int[] a = {100, 200, 300, 400, 500, 600};
        int[] l = new int[a.length/divider];

        int i = 0;
        while ( i<l.length){
            l[i] = a[i*divider];
            System.out.println(l[i]);
            i++;
        }
    }
}

答案 2 :(得分:0)

我认为你想要做的是使用&#39; loc&#39;你的阵列&#39; l&#39;。像这样:

public int[] everyOther(int[] a) {
    if (a.length < 2) {
        return a;

    }

    int[] l = new int[a.length / 2];

    int loc = 0, i = 0;
    System.out.println("size: " + a.length);
    while (i < a.length) {
        if (!isOdd(a[i])){
            l[loc] = a[i];
            loc++;
        }
        i++;            

    }

    return l;
}

这是isOdd函数

public boolean isOdd(int number) {
    return number % 2 != 0;
}

由于l.lenght设置为a.length/2,因此只有当数组a的大小为偶数时,此代码才有效。例如,如果a.legth = 9则{ {1}}将只有4,这将在执行while循环时导致l