我想从数组中提取数字,并将它们分为正数和负数,分成不同的数组。为什么我的Java代码不起作用?
如何让它发挥作用?
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]);
}
编辑:这会引发异常:(谢谢,BRjava)
ArrayIndexOutOfBoundsException
,第36行
答案 0 :(得分:3)
使用ArrayList它比普通数组好。
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);
}
}
答案 1 :(得分:2)
问题在于您有三个数组pklad[]
,pzap[]
和n[]
,但您尝试使用单个索引j
来写入所有三个数组。这就是导致ArrayIndexOutOfBoundsException
的原因:只要j
超过了较短数组的限制,尝试写入就会导致异常。
您需要三个单独的索引,例如jpos
,jneg
和jn
,所有索引都在循环之前初始化为零。当您写入相应的数组时,每个索引都需要单独递增:
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];
}
}