Question

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

Was it helpful?

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.

OTHER TIPS

Like this:

for(int printCounter = 0; printCounter <= count; printCounter++) {
    System.out.println(array1[printCounter]);
}

I guess you should print every number until you hit the negative one :) Assuming that negative number is stored in the array too

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top