-1
 int a[] = {1, 6, 3, 4, 5, 8, 7};

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

            int b = new int[3];

          b[i] = a[i];

          System.out.print(b[i] + " ");
}
}

//I want a new array b, to have the even values of a. How can I make this work?

LOTUS
  • 1
  • 2
  • Does this answer your question? [Make copy of an array](https://stackoverflow.com/questions/5785745/make-copy-of-an-array) – avocadoLambda Dec 04 '22 at 11:11
  • You are very close, you need to do 2 things here: 1/ declare the b variable as an array and add the valid answers to this. 2/ Remove the line ```int b = new int[3];``` which is setting b as an integer. – ThurstonLevi Dec 06 '22 at 13:58

2 Answers2

1

I think you need to check the ordering of your code.

Each For loop iteration, if your number meets the criteria your creating a new array called b and adding the value, however, on the next iteration, the array no longer exists so another new one is created.

In addition to this, you're also setting the index of b, based on the index of a, however, b's array only has 3 elements, therefore it will fail from index 4 onwards. So you would also need a second index to reference (in the below I've called this 'j', and you would use this to assign values to b's array

Consider declaring b under your declaration of a, then print the result outside of the for loop like so:

int[] a = new int[] {1, 6, 3, 4, 5, 8, 7};
int[] b = new int[3];
int j = 0;

for(int i = 0; i < a.length; i++) {
    if (a[i] % 2 == 0) {
        b[j] = a[i];
        j++;
    }
}
//  Output the Values of b here
for(int i = 0; i < b.length; i++) {
    System.out.print(b[i] + " ");
}

One thing to keep in mind here, that this will work for the values you've provided, however what if the values change and there are more elements in a's array? You'd need to define b with more elements, so using an array with a set length wouldn't be best practise here. Consider using a List instead.

Nick Scotney
  • 269
  • 1
  • 2
  • 11
1

There are two ways. First way introduce a new counter:

        int a[] = {1, 6, 3, 4, 5, 8, 7};
        int b[] = new int[a.length/2];
        int count = 0;
        for (int i = 0; i < a.length; i++) {
            if (a[i] % 2 == 0) {
                b[count] = a[i];
                System.out.print(b[count] + " ");
                count++;
            }
        }

The second way is to use Java Streams:

        int[] ints = Arrays.stream(a).filter(item -> item % 2 == 0).toArray();
        for (int i : ints) {
            System.out.println(i);
        }

The second way can be problematic in performance optimized environments, or if the arrays are really huge, as we need to iterate twice over the items.

See also benchmarking of Java Streams here

If you only need to print the result, you can avoid the iterations via

Arrays.stream(a).filter(item -> item % 2 == 0).forEach(System.out::println);
luckyluke
  • 491
  • 7
  • 16