Reputation: 23
I have a question about Java. I made this code to separate negative and positive numbers into 2 arrays and after that to print them. But all the time when I start that I have an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at mypackages.MyClass.main(MyClass.java:26)
Here is the code I have written:
package mypackages;
public class MyClass {
public static void main(String[] args) {
int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
int counterNeg = 0;
int counterPoz = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] < 0){
counterNeg++;
} else if (array[i] > 0){
counterPoz++;
}
}
int[] arrayNeg = new int[counterNeg];
int[] arrayPoz = new int[counterPoz];
for (int j = 0; j < array.length; j++) {
if (array[j] < 0){
arrayNeg[j] = array[j];
} else if (array[j] > 0){
arrayPoz[j] = array[j];
} else {
continue;
}
}
Upvotes: 1
Views: 83
Reputation: 311796
Previous answers to this question definitely solve the problem, but it's worth noting that this is the kind of problem you may want to use Java's streams to solve, instead of implementing it yourself:
Map<Boolean, List<Integer>> map =
Arrays.stream(array)
.filter(i -> i != 0)
.boxed()
.collect(Collectors.partitioningBy(i -> i > 0));
List<Integer> positives = map.get(Boolean.TRUE);
List<Integer> negatives = map.get(Boolean.FALSE);
Upvotes: 1
Reputation: 55
for (int a = 0, b = 0, j = 0; j < array.length; j++) {
if (array[j] < 0){
arrayNeg[a++] = array[j];
} else {
arrayPoz[b++] = array[j];
}
}
The problem lies from using j as your index to access arrayNeg and arrayPoz, remember that the sizes of each array is not equal.
Upvotes: 0
Reputation: 57154
You are accessing the arrays arrayNeg
and arrayPoz
by using the index that goes up to array.length - 1
causing a ArrayIndexOutOfBounds because both arrays are smaller than the original one.
Solution: keep track of where to insert the numbers in to the two downstream arrays:
int[] arrayNeg = new int[counterNeg];
int[] arrayPoz = new int[counterPoz];
int arrayNegCounter = 0;
int arrayPozCounter = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] < 0){
arrayNeg[arrayNegCounter] = array[j];
arrayNegCounter++;
} else if (array[j] > 0){
arrayPoz[arrayPozCounter] = array[j];
arrayPozCounter++;
} else {
continue;
}
}
Upvotes: 2