简体   繁体   中英

Loop through an array and list out in a specific way

I am trying to loop through a ListArray of 16 elements. I want to list out four elements, and then make a new line and so on. This is my code so far:

int count = 0;

for(int i = 0; i < 16; i++)
{
    count++;

    if (count == 4){
        count = 0;
        System.out.println();

    }
        System.out.println(ArrayList.get(i));   
}


My output is:
Three elements
Four elements
Four elements
Four elements
One element


This is the result I want:
Four elements, then a new line
Four elements, then a new line
And so on. Up to 16 total elements.


Element 1, Element 2, Element 3, Element 4
Element 5, Element 6, Element 7, Element 8
Element 9, Element 10, Element 11, Element 12
Element 13, Element 14, Element 15, Element 16

Try to use modulo operator for this.

for(int i = 0; i < 16; i++) {
    System.out.println(ArrayList.get(i));
    if (i % 4 == 3 && i != 15){
       System.out.println();
    }
}

Also there is a convention of having variables with the first letter in lowercase in Java so rename ArrayList to arrayList .

Use this simple loop:

for (int i = 0; i < 16; i++) {
    System.out.println(ArrayList.get(i));

    if ((i % 4) == 3) {
        System.out.println();
    }
}

Try this:

for(int i = 0; i < 16; i++)
{
    if (i > 0 && (i % 4) == 0){
        System.out.println();

    }

    System.out.println(ArrayList.get(i));   
}

That is you must increment after the if .

The i > 0 is necessary to avoid printing an empty line at the beginning.

If you move the if after printing the data:

if (i < 15 && (i % 4) == 3){
   System.out.println();
}

Without the i < 15 , you get an additional empty line after the last block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM