简体   繁体   English

java中关于copyEven的问题

[英]Questions about copyEven in java

The question is as follows:问题如下:

Write a Java method int[] copyEven(int[] nums) that copy elements at even indices to a new array.编写一个 Java 方法int[] copyEven(int[] nums)将偶数索引处的元素复制到一个新数组。

It must return the new array of the correct length with those elements inside.它必须返回包含这些元素的正确长度的新数组。

For example例如

copyEven([1, 2, 3]) → [1, 3]
copyEven([1, 2, 3, 4]) → [1, 3]

Below is my code:下面是我的代码:

public static int [] copyEven(int[] nums){
    int n =nums.length;
    int a=0;
    for (int i=0;i<n;i++){
        if (nums[i]%2 !=0){
            a++;
    }
    int c=a;
    int [] arr=new int[c];
    int b=0;
    for (int j=0;b<a;j++){
        if (nums[j]%2 !=0){
            arr[b]=nums[j];
            b++;}
        }
    }
    return arr;
}

I am just a beginner on code, and this is my first time using this website.我只是一个代码初学者,这是我第一次使用这个网站。 I searched online and found that in similar questions, the number of odd numbers is provided.我在网上查了一下,发现在类似的问题中,提供了奇数的个数。 Thus, I plan to use a in the code to count the number of odd numbers at first, then create a new array to finish the question.因此,我打算先在代码中使用a来计算奇数的数量,然后创建一个新数组来完成问题。 However, NetBeans told me that in int [] arr=new int[c] ,the array is written to,never read from.但是,NetBeans 告诉我在int [] arr=new int[c] ,数组被写入,从不读取。 I do not understand what that means.我不明白这是什么意思。 I would appreciate it very much if you can help me, thank you!如果您能帮助我,我将不胜感激,谢谢!

Here you can get all elements at even indices.在这里,您可以获取偶数索引处的所有元素。
Indexing started from 1 as your given examples said.正如您给出的示例所说,索引从 1 开始。

public static int[] copyEven(int[] nums) {
    int length = nums.length;
    int numberOfEvenNumbers = (length % 2 == 0) ? length / 2 : length / 2 + 1;

    int[] copy = new int[numberOfEvenNumbers];
    int index = 0;

    for (int i = 0; i < nums.length; i += 2) {
        copy[index] = nums[i];
        index++;
    }
    return copy;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM