1

Can you please advise how can I pass results from an array to another array without some numbers? In this case without zero numbers. Here is my code, I'm stuck.

Result is: [0, 1, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11] - all I want to do, is to create another array and pass there numbers from above without 0's.

Thanks.

public class SieveOfEratosthenes {
    public static void main(String[] args) {
        int[] myArray = new int[12];

        fillArrayWithNumbers(myArray);

        System.out.println(Arrays.toString(sieve(myArray)));

    }

    private static void fillArrayWithNumbers(int[] myArray) {
        for (int i = 0; i < myArray.length; i++) {
            myArray[i] = i;
        }
    }

    public static int[] sieve(int[] maximumNumber) {
        for (int j = 2; j < maximumNumber.length; j++) {
            for (int i = j * 2; i < maximumNumber.length; i += j) {
                maximumNumber[i] = 0;
                }
        }
        return maximumNumber;
    }
}
  • What have you tried so far? You can use `if( myArray[i] == 0 ){ }` to check, whether an array element is e.g. `0`, or `if( myArray[i] != 0){ }` to check if it is not e.g. `0`. – infinitezero May 04 '18 at 16:21

3 Answers3

3

You can convert your Int[] to a Stream and filter out the zero values.

Code

public static void main(String[] args) {
    int[] arr = new int[]{0, 1, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11};

    int[] ints = Arrays.stream(arr)
            .filter(i -> i != 0)
            .toArray();

    Arrays.stream(ints).forEach(System.out::println);

}

Output

1
2
3
5
7
11
Garreth Golding
  • 985
  • 2
  • 11
  • 19
1

The solution is above as what infinitezero said to write a for loop that has you array length. Then copy items in the array as length.

for(int i = 0; i < arr.length; i++){
  if(arr[i] == 0){

  }
  else{
    arr[i] = arr2[i];
  }
Max S
  • 11
  • 6
0

I think you can create a new array and fill it with above zero value: What you want to do it to omit all even numbers (except 2). Then it should be done like this:

public static int[] sieve(int[] maximumNumber) {
    int[] result = new int[maximumNumber.length];
    int index= 0;

    for (int i = 1; i < maximumNumber.length; i++) {
        if (i == 2 || i % 2 != 0) { // i is 2 or odd
           result[index] = i;
           index++; // This will store the real length of the array
        }
    }
    return Arrays.copyOfRange(result, 0, index);
}
Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51
  • This answer doesn't really reflect the question. The original post asked about creating a new array from an existing array without any zeroes. – Garreth Golding May 04 '18 at 16:35