Search code examples
javaarraysprimitive

Print an array in java without empty spaces


I am writing a piece of code where someone types in numbers that are added to an array. They can type in a negative number to stop.

   int loop1 = 0;
   int[] array1;
   array1 = new int[10000];
   boolean escape = false;
   int count = 0;
   while (escape == false){
     loop1 = scan.nextInt();
     count ++;
     if (loop1 >= 0){
       array1[count] = loop1;
     }else{
       escape = true;
     }
   }

There are exactly 10000 spaces in the primitive array. How could I print out the array without the empty spaces


Solution

  • for( int a:array1){
       if(a>=0){
          System.out.println(a);
       }
    }
    

    When you initialize the array, all index values set to 0, and you would 0 check. As a different approach, you could use ArrayList to insert values, which will save you from creating un wanted large array.