-2

I am trying to format the output from what I have written to display a list of primes (Eratosthenes) to a certain number results per line. Do they need to placed into an Array to accomplish this? I have not come across a way to implement their division besides .split("");, which would render a single line for each and the Oracle site's System.out.format(); argument index to specify length. Yet, these require the characters to be known. I am printing it with the following, which of course creates an infinite line.

  for (int count = 2; count <= limit; count++) { 
        if (!match[count]) { 
            System.out.print(count + ", ");
        } 
   }

Is there a way to simply call System.out.print("\n"); with an if(...>[10] condition when System.out.print() has run for instance 10 times? Perhaps I am overlooking something, relatively new to Java. Thanks in advance for any advice or input.

Austin
  • 195
  • 1
  • 4
  • 13

3 Answers3

2

By using a tracker variable, you can keep track of how many items have been displayed already so you know when to insert a new line. In this case, I chose 10 items. The exact limit is flexible to your needs.

...
int num = 0;
//loop
for(int count = 2; count <= limit; count++)
{
    if(!match[count])
    {
        if (num == 10) { System.out.print("\n"); num = 0; }//alternatively, System.out.println();
        System.out.print(count + ",");
        num++;
    }
}
...
D. Ben Knoble
  • 4,273
  • 1
  • 20
  • 38
1

You can just simply create some int value e.g.

int i = 1;

...and increment it's value everytime Sysout is running.

Something like this:

 int i = 1;
 for (int count = 2; count <= limit; count++) { 
    if (!match[count]) {
        if (i%10 == 0) 
            System.out.print(count+ "\n");
        else 
            System.out.print(count + ", ");
        i++;
    } 
}
hpopiolkiewicz
  • 3,281
  • 4
  • 24
  • 36
  • 1
    This worked perfectly thank you! Only addition is that `System.out.print(count + ", \n");` keeps the comma when `if` gets called. – Austin Jun 12 '15 at 22:23
1

Try this:

int idx=1;
int itemsOnEachLine=10;
for(int count = 2; count <= limit; count++)
{
    if(!match[count])
    {
        System.out.print(count+(idx%itemsOnEachLine==0?"\n":","));
        idx++;
    }
}

you go increasing a counter (idx) along with every write, every 10 increments (idx modulus 10 == 0), you will be printing a new line character, else, a "," character.