2

I have to make two new arrays from this existing one, one will have positive values, and one negative, not including 0. If this logic is right, I only have one problem, declaring the length of these two, new arrays. I'm a beginner in programming.

public static void main(String[] args) {
    int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
    int[] array1 = new int [];
    int[] array2 = new int [];
    for(int i=0; i<array.length; i++) {
    if(array[i]>0) {
        if(array[i]==0)
            continue;
        int[] array1 = new int[];

        array1[i]=array[i];
    } else if(array[i]<0) {
        if(array[i]==0)
            continue;

        array2[i]=array[i];
    }
}
3
  • Checking if(array[i]==0) inside the if(array[i]>0) block, makes no sense. Commented Nov 18, 2016 at 14:50
  • Your code doesnt compile, you must declare the size of the array first. You should iterate on array and count how many positives and negatives elements are. Then, instantiate array1 and array2 with the given size Commented Nov 18, 2016 at 15:02
  • ok, I ll try that out, ty! Commented Nov 18, 2016 at 15:13

2 Answers 2

4

If you use Java 8 then you could just do

int[] array = new int[]{12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};

int[] positives = Arrays.stream(array).filter(x -> x > 0).toArray();
int[] negatives = Arrays.stream(array).filter(x -> x < 0).toArray();
Sign up to request clarification or add additional context in comments.

2 Comments

I have to use loops because that's what we are learning now, this is my assignment, to pratctice arrays and loops. :/
Then you have to do as dasblinkenlight explained
1

You need to change your algorithm to do it in two passes, like this:

  • Go through the array once, and count how many items will end up in each sub-array
  • Instantiate the arrays with the counts obtained during the first step
  • Go through the array again, and populate the results.

When you implement this, node that this code uses incorrect index for array1 and array2:

array1[i] = array[i];
array2[i] = array[i];

You need two separate indexes for each side:

array1[positiveIndex++] = array[i];
array2[negativeIndex++] = array[i];

Alternatively, you could use a collection that can grow as you add items to it (e.g. ArrayList<Integer>) if your exercise allows for it. This approach is a lot simpler, because it requires only a single pass.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.