That error means you are assigning to a null pointer,
you could write arr[a.length]
but that would allocate
memory for more elements than you actually need, because
you need to only store according to a condition,
that way you should do it like this:
public class Omit {
int[] omitnum(int[] a) {
int maxNum = 0;
// calculate how much memory needed
for(int i = 0;i < a.length; i++) {
if(!(a[i] >= 13 && a[i] <= 19)) {
maxNum++;
}
}
// --------------------------------
int[] arr = new int[maxNum];
for(int i = 0, j = 0; i < a.length; i++) {
if(a[i] >= 13 && a[i] <= 19) {
System.out.println("Deleted: " + a[i]);
}else {
/* we can't use `i` because that would gives an error
because arr has less elements than a :) */
arr[j++] = a[i];
}
}
return arr;
}
public static void main(String[] args) {
Omit c = new Omit();
int[] a = {1, 2, 3, 12, 113, 14, 19, 20};
int[] b = c.omitnum(a);
for(int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
}
}
Output:
Deleted: 14
Deleted: 19
1
2
3
12
113
20
and array.length
gives you flexibility instead of
looping to a static position, to avoid changing
your code each time you add or remove elements,
and from counting of course
Here is another way using ArrayLists
import java.util.ArrayList;
public class Omit {
ArrayList omitnum(int[] a) {
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i = 0; i < a.length; i++) {
if(a[i] >= 13 && a[i] <= 19) {
System.out.println("Deleted: " + a[i]);
}else {
arr.add(a[i]);
}
}
return arr;
}
public static void main(String[] args) {
Omit c = new Omit();
int[] a = {1, 2, 3, 12, 113, 14, 19, 20};
ArrayList b = c.omitnum(a);
for(int i = 0, n = b.size(); i < n; i++) {
System.out.println(b.get(i));
}
}
}
Output:
Deleted: 14
Deleted: 19
1
2
3
12
113
20
Here is another way suggested by the user Abra, but I made
some changes to preserve the default behaviour of printing
import java.util.Arrays;
public class Omit {
static boolean printN(int n) {
System.out.println("Deleted: " + Integer.toString(n));
return false;
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 12, 113, 14, 19, 20};
int[] b = Arrays.stream(a).filter(n -> n < 13 || n > 19 ||
printN(n)).toArray();
for(int i = 0;i < b.length; i++) {
System.out.println(b[i]);
}
}
}
Output:
Deleted: 14
Deleted: 19
1
2
3
12
113
20