尝试只打印此数组方法中的特定数字



由于某种原因,我只设法打印奇数,但它仍然以某种方式打印看起来是null的值。我试图只打印返回为奇数的值。

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中使用指定大小的int数组时,它将数组中的每个值设置为0。这样做将删除末尾所有无关的0。

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

下面是修改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]