关于 Java 中的 copyEven 的问题

huangapple go评论73阅读模式
英文:

Questions about copyEven in java

问题

以下是您的代码的翻译部分:

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;
}

关于您提到的问题,"the array is written to, never read from" 的意思是,代码中声明了一个新的数组 arr,但在第二个循环中,您只在循环体内将元素写入该数组,而没有在后续的代码中对该数组进行读取或使用。这可能会导致编译器给出警告或错误,因为您声明了一个数组,但似乎在后续的代码中没有使用到它。要解决这个问题,您需要确保在创建并写入数组后,代码中还需要使用该数组进行进一步的操作。

英文:

The question is as follows:

Write a Java method int[] copyEven(int[] nums) that copy elements at even indices to a new array.

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&lt;n;i++){
        if (nums[i]%2 !=0){
            a++;
    }
    int c=a;
    int [] arr=new int[c];
    int b=0;
    for (int j=0;b&lt;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. However, NetBeans told me that in int [] arr=new int[c],the array is written to,never read from. I do not understand what that means. I would appreciate it very much if you can help me, thank you!

答案1

得分: 0

以下是您要翻译的内容:

在这里,您可以获得所有偶数索引处的元素。<br>根据您提供的示例,索引从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 &lt; nums.length; i += 2) {
        copy[index] = nums[i];
        index++;
    }
    return copy;
}
英文:

Here you can get all elements at even indices. <br> Indexing started from 1 as your given examples said.

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 &lt; nums.length; i += 2) {
        copy[index] = nums[i];
        index++;
    }
    return copy;
}

huangapple
  • 本文由 发表于 2020年10月12日 19:09:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64316686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定