简体   繁体   中英

create array of negative integers

trying to put all negative ints in array

int[] a = {1,2,3,-4,-5,-5,-9};

into separate array, this code produces 'array out of bounds' not sure why

    int[] negatives(int[] a){
    int count = 0;
    int[] na = new int[0];
    for(int i=0;i<a.length;i++){
        if(a[i]<0){
            count++;
            na=new int[count];
            a[i] = na[i];
        }
    }

         System.out.print(na.length);//<-shows correct size for resulting array

    return na;
}

console output for na.length gives correct size. thanks any help

int[] na = new int[0];
                   ↑

na is of size 0, it can has no elements at all. Do:

int[] na = new int[a.length];

And do this outside the method.

If you want the sizes to be the same, you have to use an ArrayList instead:

ArrayList<Integer> na = new ArrayList<>();

And after filling it, you can easily convert it back to an array.

Although your code looks wrong in several ways, I believe these are the lines that are causing the exception:

        na=new int[count];
        a[i] = na[i];

You are creating an array for na with count elements; then on the next line you are accessing element i of that array. It is the case that i will be >= count , so the access is out of bounds.

Also worth noting is that the array you create is uninitialised, so even if the index were not out of bounds, you are effectively just assinging a 0 to a[i] .

Kind of hit upon in the previous answer, reallocating a new array per new negative integer found is not efficient at all, especially considering you need to copy over the "old" na values into the newly allocated na to keep a running total...

To answer your question, to avoid the out of bounds exception it should be,

na[count-1]=a[i];

But, like the previous comment alluded to, create an array first equal to the size of "a" and then you can just add elements as needed without having to create a new array and copy over the elements.

At the end, instead of printing na.length just print out count. And if want the negative values, just in a for loop have count has you max condition.

for(int j=0; j< count; j++)
//....

Finally, I would suggest using an ArrayList instead of an array for na if possible.

Here's a way to do it without worrying about what size your array is, and still returning an array of ints.

int[] negatives(int[] a){

   ArrayList<Integer> negatives = new ArrayList<Integer>();

    for(int i=0;i<a.length;i++){
        if(a[i]<0){
            negatives.add(a[i])
        }
    }

    int[] na= negatives.toArray(new int[negatives.size()]);
    return na;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM