Java Collection How to - Output Array to console, 10 number per line








Question

We would like to know how to output Array to console, 10 number per line.

Answer

/*w w  w  . ja v  a  2s. c o m*/
public class Main {
  public static void main(String[] args) {
    int[] list = new int[100];

    for (int i = 0; i < list.length; i++) {
      list[i] = (int) (Math.random() * 50 + 1);
    }

    int elementInOneLine = 0;

    for (int i = 0; i < list.length; i++) {
      if (elementInOneLine == 10) {
        System.out.println();
        elementInOneLine = 0;
      }
      System.out.print(list[i] + " ");
      elementInOneLine++;
    }
  }
}

The code above generates the following result.