尝试在此数组方法中仅打印特定数字

Trying to only print specific numbers in this Array Method

出于某种原因,我只打印了奇数,但它仍然以某种方式打印出看似为空的值。我试图只打印返回为奇数的值。

public class Odd {

    public int[] removeEvens(int [] nums) {  //start of method
           
        int [] newArray = new int[nums.length];
        
        int count = 0;
        
        // start of array conversion
        for(int i = 0; i < nums.length; i++) {
                    
            newArray[count] = nums[i];
            count++;
            
            }
        
        int counter = 0;
        for (int i = 0; i < nums.length; i++) 
            if (newArray[i] % 2 == 1)
                newArray[counter++] = newArray[i];
        for (int i=counter; i < nums.length; i++)
            newArray[i] = 0;  
        
          
                    
    return newArray;    
    }
        // end of method 

    public static void main(String[] args) {
        Odd labObject = new Odd();
          int [] input = {1,2,3,4,5,6,7,8,9};
          int [] result = labObject.removeEvens(input);
          
          // Helper method Arrays.toString() converts int[] to a String
          System.out.println(Arrays.toString(result)); // Should print [1, 3, 5, 7, 9]

    }

}

将其更改为 return Arrays.copyOfRange(newArray, 0, counter); 当您在 java 中创建具有指定大小的整数数组时,它将数组中的每个值设置为 0。这样做将删除所有无关的 0最后。

这可以通过在创建新数组之前先确定新数组的正确大小来轻松解决。然后简单地循环数组并只存储奇数。否则,remove/trim 返回前的数组大小。

这是修改您的 removeEvens 方法的解决方案:

public int[] removeEvens(int[] nums)
{  //start of method

    int count = 0;

    // start of array conversion
    // Count the odd numbers to work out the array length
    for (int i = 0; i < nums.length; i++)
    {
        if (nums[i] % 2 == 1 || nums[i] % 2 == -1)
        {
            count++;
        }
    }

    // Now create a new array of the correct length
    int[] newArray = new int[count];

    // Now loop through the original array and only store the odd numbers in the new array
    int counter = 0;
    for (int i = 0; i < nums.length; i++)
    {
        if (nums[i] % 2 == 1 || nums[i] % 2 == -1)
        {
            newArray[counter] = nums[i];
            counter ++;
        }
    }

    // Return the result
    return newArray;
}

结果:

[1, 3, 5, 7, 9]