Writing a function that takes an array and returns only the positives

时间:2017-03-22 18:46:29

标签: java arrays

For my lab, I need to write a static function called getPositiveNumbers that takes an argument of int[] numbers, and returns a new array with only the positive numbers in that array. I know that I first need to count how many positive numbers are in the array, and then create a new array of that size. I'm wondering how should I go about filling that new array with only the positive numbers. Any help would be appreciated, as I'm really trying to learn java. The following is what I currently have written. Thanks!

    public class Example1 {

    public static int[] getPositiveNumbes(int[] numbers)
    {
        int total = 0;
        for (int i = 0; i < numbers.length; i +=1)
        {
            if (numbers[i] > 0)
            {
                total += 1;
            }
        }
        int[] nums = new int[total];
        for ( int i = 0; i< numbers.length; i+= 1)
        {
            if (numbers[i] > 0)
            {
                for(int j = 0; j<total; j+=1)
                {
                    nums[j] = numbers[i];
                }
            }
        }
        return nums;
    }
}

1 个答案:

答案 0 :(得分:4)

You do not need the inner for. Just use index j to keep track of last place you filled the num array.

public class Example1 {

public static int[] getPositiveNumbes(int[] numbers)
{
    int total = 0;
    for (int i = 0; i < numbers.length; i +=1)
    {
        if (numbers[i] > 0)
        {
            total += 1;
        }
     }
     int[] nums = new int[total];
     int j = 0;
     for ( int i = 0; i < numbers.length; i+= 1)
     {
         if (numbers[i] > 0)
         {
             num[j] = number[i];
             j++;
         }
     }
     return nums;
 }