suck_at_coding18 suck_at_coding18 - 1 month ago 16
Java Question

Using arrays to get positive numbers

I'm trying to return the positive numbers in an array. I'm new to arrays and am having trouble figuring it out.

public class PossitiveArray
{
public static void main(String[] args) {
int[] numbers = {2,-1,5,-4,3};
System.out.print(numbers);

}
public static int[] getPositiveNumbers(int[] numbers)
{

for (int n : numbers)
{
if(n>0)
{
int [] nums = numbers;
}
}

return nums;

}
}


Analysis-
This is what I came up with. As it is right now it gives me and error saying I need to make a local variable for nums but when I do that it returns "[I@677327b6". I tried to make it return numbers but i'm not sure what to put into the if statement.

Required-
The goal is to just have positive numbers returned. Any help would be appreciate I am very knew to arrays and programing in general.

Answer

Use below Code-

public class test
{
    public static void main(String[] args) {
     int[] numbers = {2,-1,5,-4,3};
     for(int n : getPositiveNumbers(numbers)){
         System.out.print(n);    
     }


    }
    public static int[] getPositiveNumbers(int[] numbers)
{
    int count = 0;
     for (int n : numbers)
     {
         if(n>0)
         {
            count++;
         }
     }
    int [] nums = new int[count];
    int i =0;
    for (int n : numbers)
    {
        if(n>0)
        {
           nums[i] = n;
           i++;
        }
    }

    return nums;

}
}
Comments