-4

I will post my code and hope someone can tell what to change to make a "dynamic array"? The current code works but they told me it is not the correct way and instead of this I need to make a dynamic array. Thanks in advance.

public static void main(String[] args) {

int i,a,b;
int [] array1 = new int[20];//{12,23, -22, 0, 43,545, -4, -55,43, 12,0, -999, -87

array1[0] = 12;
array1[1] = 23;
array1[2] = -22;
array1[3] = 0;
array1[4] = 43;
array1[5] = 545;
array1[6] = -4;
array1[7] = -55;
array1[8] = 43;
array1[9] = 12;
array1[10] = 0;
array1[11] = -999;
array1[12] = -87;

int [] arrayPlus = new int[20];
int [] arrayMinus = new int[20];


a=b=0;


for (i = 0; i < 13; i++) {
    if (array1[i] > 0 || array1[i] == 0) {
        arrayPlus[a] = array1[i];
        a++;
    } else {
        arrayMinus[b] = array1[i];
        b++;
    }
}
System.out.println("Positive array numbers");
for (i = 0; i < a; i++) {
System.out.println(arrayPlus[i]);}


System.out.println("");

System.out.println("Negative array numbers");
for (i = 0; i < b; i++) {
System.out.println(arrayMinus[i]);}

}
}
3
  • Maybe they're asking for an array that's initialised with a variable length at runtime? Or maybe they're referring to ArrayLists? Could you tell us what the code is supposed to be doing? Commented Dec 17, 2015 at 9:58
  • It must be dynamically determined number of target in array Commented Dec 17, 2015 at 10:00
  • Another Student project? Commented Dec 17, 2015 at 10:36

1 Answer 1

0

Please check the below code

      import java.util.Scanner;
      class DynamicArray {
      public static void main(String[] args) {

      int i,a,b;
      System.out.println("Enter the limit of array :" );
      Scanner s = new Scanner(System.in);
      int limit = s.nextInt();
      int [] array1 = new int[limit];//{12,23, -22, 0, 43,545, -4, -55,43, 12,0, -999, -87

      System.out.println("Enter the numbers");
      for(i=0; i<limit; i++)
      {
          array1[i] = s.nextInt();
      }
      int [] arrayPlus = new int[limit];
      int [] arrayMinus = new int[limit];


     a=b=0;


    for (i = 0; i < limit; i++) {
         if (array1[i] > 0 || array1[i] == 0) {
              arrayPlus[a] = array1[i];
              a++;
        } else {
              arrayMinus[b] = array1[i];
              b++;
        }
   }
   System.out.println("Positive array numbers");
   for (i = 0; i < a; i++) {
       System.out.println(arrayPlus[i]);}


       System.out.println("");

       System.out.println("Negative array numbers");
       for (i = 0; i < b; i++) {
            System.out.println(arrayMinus[i]);}

       }
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Works for me but Im waiting to see what the professor says. I let you know. Thank You for your help friend.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.