Algorithm output to length starts new line

183 views Asked by At

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.

3

There are 3 answers

1
hpopiolkiewicz On BEST ANSWER

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++;
    } 
}
2
D. Ben Knoble On

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++;
    }
}
...
0
Daniel Rodriguez On

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.