出于某種原因,我只能列印奇數,但它仍然以某種方式列印似乎為空的值。我試圖只列印回傳為奇數的值。
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]
}
}
uj5u.com熱心網友回復:
將其更改為return Arrays.copyOfRange(newArray, 0, counter);當您在 java 中創建具有指定大小的整數陣列時,它將陣列中的每個值設定為 0。這樣做將在最后洗掉所有無關的 0。
uj5u.com熱心網友回復:
這可以通過在創建新陣列之前先計算出新陣列的正確大小來輕松解決。然后簡單地回圈陣列并只存盤奇數。否則,在回傳之前洗掉/修剪陣列大小。
這是通過修改您的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)
{
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)
{
newArray[counter] = nums[I];
counter ;
}
}
// Return the result
return newArray;
}
結果:
[1, 3, 5, 7, 9]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321517.html
上一篇:如何根據條件對物件陣列進行排序?
