How can I make a new Array and copy all the postive elements from the other array in the new array and return it?

Erik Macias :

This method returns an array that contains the positive elements of the parameter array in. To do that, compute the number of positive elements in the array in and store the obtained value in the variable nElements of type integer, declare the double array output of size nElements, copy the positive elements of in into the array output, and return the array output. If all the elements of the array in are non-positive, your method should return an array of size 1 and the only element of the returned array is assigned the value -1.

My question here is when I run my program it states Exception in thread "main" java.lang.NegativeArraySizeException and I don't know how to take it out and only return the positive elements.

The Java-Code:

public static double [] partialPositiveArray(double [] in)

   {

   int nElements = 0;

   for(int i = 0; i < in.length; i++)
   {
     if(in[i] > 0)
     {
        nElements = (int)in[i];

     }
     else if(in[i] <= 0)
     {
        nElements = -1;
     }
  }
  double [] output = new double[nElements];


  for(int i = 0; i < in.length; i++)
  {
     output[i] = nElements;

  }

  return output;

  }
SwissCodeMen :

with this code you will add all positive numbers. the sum in this example is 60.7 and for all negative numbers it will write -1 in the negative-array. in this example twice.

Code:

public class NegativeAndPositiveNumbers {
    public static void main(String[] args) {
        double[] arr = {25.0, -7.0, 10.7, 25.0, -64.0};
        System.out.println(partialPositiveArray(arr));

        int negative[] = negativeArray(arr);
        for (int i = 0; i < negative.length; i++){
            System.out.print(negative[i] + " ");
        }
    }

    public static double partialPositiveArray(double[] in) {
        double nElements = 0;

        for (int i = 0; i < in.length; i++) {
            if (in[i] > 0) {
                nElements += in[i];
            }
        }
        return nElements;
    }

    public static int[] negativeArray(double[] in) {
        int[] negativeWithZero = new int[in.length];
        int index = 0;

        for (int i = 0; i < in.length; i++) {
            if (in[i] <= 0) {
                negativeWithZero[index] = -1;
                index++;
            }
        }
        int[] negative = new int[index];

        for (int j = 0; j < negative.length; j++){
            negative[j] = negativeWithZero[j];
        }

        return negative;
    }
}

I think it could be solved more easily, but it works anyway. I hope everything is clear

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=320675&siteId=1
Recommended