0

I've got a problem to solve as follows:

Create a method that returns an array that contains only the positive values of another int[] a

I've kinda solved it by writing this method:

public static int[] soloPositivi(int[] a) {
    int[] pos = new int[a.length];
    int j=0;

    for (int i=0; i<a.length; i++){
        if (a[i]>0) {
            pos[j] = a[i];
            j++;
        }
    }
    return pos;
}

of course when I test it using for example:

int[] a = new int[] {2,-3,0,7,11};

I get [2,7,11,0,0], because I set:

int[] pos = new int[a.length];

The question is, how do I get the pos array to have a modular length so that I can get [2,7,11], without having to use lists? I have to solve this problem by only using Arrays methods.

Daniele
  • 4,163
  • 7
  • 44
  • 95
  • don't use an array and use a list? –  Jun 11 '16 at 09:38
  • This problem is meant to be solved only by using arrays and their methods... If I could have used lists I would have done it – Daniele Jun 11 '16 at 09:40
  • Use `ArrayList` to add valid value, and then use `toArray()` method to `return` an array. https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html – Đăng Khoa Huỳnh Jun 11 '16 at 09:41
  • You can look at the linked question - although some answers do mention using a list, others also suggests first computing the size of the array, and then creating it with this size. – Tunaki Jun 11 '16 at 09:42
  • There is also the possibility to improve the code with `Java8`: `int[] arr = new int[] {2,-3,0,7,11};` `int[] newArr = Arrays.stream(arr).filter(x -> x > 0).toArray();` maybe this solution can also be added? – wake-0 Jun 11 '16 at 09:50

1 Answers1

3

First, loop through and count the number of positive elements to know the length, then loop through again to copy.

public static int[] copyPositiveVals(int[] arr) {
    int count = 0;
    for(int x : arr) {
        if (x > 0) count++;
    }

    int[] arr2 = new int[count];
    int i = 0;
    for(int x : arr) {
        if (x > 0) {
             arr2[i] = x;
             i++;
        }
    }
    return arr2;
}
Mshnik
  • 7,032
  • 1
  • 25
  • 38
  • This should solve it, I didn't think about using two loops. Thanks – Daniele Jun 11 '16 at 09:42
  • I think for the given problem using `Java 8` is much easier: `int[] arr = new int[] {2,-3,0,7,11};` `int[] newArr = Arrays.stream(arr).filter(x -> x > 0).toArray();` – wake-0 Jun 11 '16 at 10:11
  • @KevinWallis I'm sure yours is a good method too, but I'm quite new to java and I was looking for a moe beginner-friendly approach – Daniele Jun 11 '16 at 11:03
  • @Daniele okay but maybe you also make yourself friendly with `java 8` lambda expressions they are quite cool and easy to use. Much more readable (fluent) than working with the default way :) – wake-0 Jun 11 '16 at 11:16