Home > front end >  Trying to only print specific numbers in this Array Method
Trying to only print specific numbers in this Array Method

Time:10-19

For some reason I have only managed as far as printing the odd numbers, but it somehow still prints what appears to be values that are null. I am trying to only print the values that returned as odd.

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]

    }

}

CodePudding user response:

change it to return Arrays.copyOfRange(newArray, 0, counter); when you make in array of ints in java with a specified size, it sets every value in the array to 0. Doing this will remove all of the extraneous 0s at the end.

CodePudding user response:

This can be easily solved by working out the correct size of the new array first before you create it. Then simply loop the array and only store the odd numbers. Otherwise, remove/trim the array size before returning it.

Here is a solution by modifying your removeEvens method:

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

Result:

[1, 3, 5, 7, 9]
  • Related