Reputation: 45
What I mean by that is when I print, for example, a Sieve of Eratosthenes, it just prints a long line of numbers vertically with println()
. With print()
, it just prints another long line horizontally. I want it so that there's some sort of line you can't go across to.
I attached a snip and for a clearer objective, I drew a red box of where I want the numbers to stop, and where to start.
Upvotes: 1
Views: 284
Reputation: 1665
There are many ways to achieve this. Here is one way. Suppose you are printing natural numbers from 1 to n
and you want only 10 natural numbers in a line, then you can do this:
for (int i = 1; i <= n; i++) {
System.out.print(i + " ");
//Add new line if there are 10 elements in a row
if (i % 10 == 0) System.out.println();
}
If you are working with Sieve of Eratosthenes
, then the numbers to be printed do not follow a regular sequence. In that case, you can count the number of numbers
printed and add a new line accordingly.
Suppose you have a boolean
array numbers
where if the index of the array represents a Prime number, then at that index true
is stored or else false
is stored. In that case you may use this:
int count = 0;
for (int i = 1; i <= n; i++) {
if (numbers[i]) {
System.out.print(i + " ");
count++;
}
if (count == 10) {
System.out.println();
count = 0;
}
}
I should add, if you still want to add more symmetry in your output so that there is proper spacing and the elements appear one below the other, you can replace System.out.print (i + " ")
with
System.out.print (i + "\t")
.
The output will appear more beautiful and it will be more readable.
I hope I have helped you.
Upvotes: 2
Reputation:
You can use IntStream
for this purpose:
IntStream.rangeClosed(11, 40)
// print elements in one line
.peek(i -> System.out.print(i + " "))
// after every tenth element
.filter(i -> i % 10 == 0)
// print new line
.forEach(i -> System.out.println());
Output:
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
Upvotes: 0