简体   繁体   中英

How to display 10 numbers per line? -Beginner-

I am currently working on a program involving arrays and I have generated 200 random numbers ranging between 0-100. But I cannot display all the numbers, 10 per line. This is my current code:

import java.util.Random;

public class RandomStats {

    public static void main(String[] args) {
        Random random = new Random ();

        for(int i=0; i<200; i++){
            int randomNumber = random.nextInt(100);
            System.out.println("Generated 200 random numbers: " + randomNumber);
        }       
    }
}
  • System.out.println() prints what you tell it, and moves to the next line.
  • System.out.print() , however, prints stuff and stays on the same line. Next call to System.out.print() will continue on the same line.

Play with that.

you basically need two loops, the outside loop goes through [0-200), and the internal loop prints out 10 numbers per line:

for (int i = 0; i < 200; i++)
{
   for (int j = 0; j < 10; j++)
   {
     System.out.print(randomNumber + " ");
   }
   System.out.print("\n");  // change to a new line
}

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