Reputation: 355
I want to extract numbers from an array and divide them into positives and negatives into separate arrays. Why does my Java code does not work?
How to make it work?
int pole[] = new int[20];
int pock = 0;
int pocz = 0;
int pocn = 0;
for (int i = 0; i < pole.length; i++) {
pole[i] = (int)(-10+Math.random()*21);
}
for (int i = 0; i < 10; i++) {
if(pole[i]>0)pock++;
else if(pole[i]<0) pocz++;
else pocn++;
}
int pklad[] = new int[pock];
int pzap[] = new int [pocz];
int n[] = new int [pocn];
int j = 0;
for (int i = 0; i < pole.length; i++) {
if(pole[i]>0){
pklad[j] = pole[i];
}if(pole[i]<0){
pzap[j] = pole[i];
}else n[j]=pole[i];
j++;
}
System.out.print("All positives: ");
for (int i = 0; i < pock; i++) {
System.out.print(pklad[i]+",");
}
System.out.println();
System.out.print("All negatives: ");
for (int i = 0; i < pocz; i++) {
System.out.println(pzap[i]);
}
System.out.print("Zeros: ");
for (int i = 0; i < pocn; i++) {
System.out.println(n[i]);
}
Edit: This throws an exception: (thanks, BRjava)
ArrayIndexOutOfBoundsException
, line 36
Upvotes: 1
Views: 86
Reputation: 726539
The problem is that you have three arrays, pklad[]
, pzap[]
, and n[]
, but you try using a single index j
to write to all three. This is what is causing your ArrayIndexOutOfBoundsException
: as soon as j
goes past the limit of the shorter of the arrays, an attempted write causes the exception.
You need three separate indexes, say, jpos
, jneg
, and jn
, all initialized to zero before the loop. Each index needs to be incremented individually when you write to its corresponding array:
for (int i = 0; i < pole.length; i++) {
if (pole[i] > 0) {
pklad[jpos++] = pole[i];
} else if (pole[i] < 0) {
pzap[jneg++] = pole[i];
} else {
n[jn++]=pole[i];
}
}
Upvotes: 2
Reputation: 194
Use the ArrayList it is better than normal arrays.
public static void main(String[] args) {
ArrayList<Double> yourNumbers = new ArrayList<Double>();
yourNumbers.add(54.2); //add some number to our array
yourNumbers.add(-67.7);
ArrayList<Double> positive = new ArrayList<>();
ArrayList<Double> negative = new ArrayList<>();
for(Double currentNumber : yourNumbers) {
if(currentNumber >= 0) {
positive.add(currentNumber);
}else if(currentNumber <0) {
negative.add(currentNumber);
}
}
//print all positive numbers
for(Double currentDouble : positive) {
System.out.println("Positive: "+currentDouble);
}
//print all negative numbers
for(Double currentDouble : negative) {
System.out.println("Negative: "+currentDouble);
}
}
Upvotes: 3