Home > OS >  How can I start a new line after every 5th number in an array?
How can I start a new line after every 5th number in an array?

Time:10-02

I'd like to get some help for my performance task, one of the requirements is to print the random generated numbers in an array to print in a 2x5 table. Here is code so far:

private static void rdnum() {
        // TODO Auto-generated method stub
        Random rd = new Random();
          int[] arr = new int[20];
          for (int i = 0; i < arr.length; i  ) {
              for (int row = 0; i < arr.length; i  ) {
             arr[i] = rd.nextInt(11); 
             System.out.print(i "\t" arr[i]); 
             
          }
              }

CodePudding user response:

You can make a new line after 5 numbers were printed. This code will print 5 pairs of numbers, the element number and the random value, in 4 rows, for a total of 20 random numbers.

private static void rdnum() {
    // TODO Auto-generated method stub
    Random rd = new Random();
    int[] arr = new int[20];
    for (int i = 0; i < arr.length; i  ) {
        arr[i] = rd.nextInt(11);
        System.out.print(i   "\t"   arr[i]);
        if (i % 5 == 0) {
            System.out.println();
        }
    }
}
  • Related