How do I make it so that it is only 6 numbers on each line when using a for-loop?
Where and how can I use the System.out.print("\n");
?
for (int i=0; i<=100; i++) {
System.out.print(i+",");
}
How do I make it so that it is only 6 numbers on each line when using a for-loop?
Where and how can I use the System.out.print("\n");
?
for (int i=0; i<=100; i++) {
System.out.print(i+",");
}
You can use the %
operator to see if i
is divisible by 6
. Since i
starts at zero, we must check to see if the remainder is equal to 5
for(int i=0;i<=100;i++){
System.out.print(i+",");
if(i % 6 == 5) {
System.out.println();
}
}
The %
operator
divides one operand by another and returns the remainder as its result.
I found out I could use a counter and a if
for(int i = 0; i <= 100; i++){
counter++;
System.out.print(i + ",");
if(counter == 6){
System.out.print("\n");
counter = 0;
}
}
Using Java-8 IntStream and collect
:
AtomicInteger atomicInteger = new AtomicInteger(0);
int size = 6;
int startingRange = 1;
int endingRange = 20;
IntStream.rangeClosed(startingRange, endingRange).boxed()
.collect(Collectors.groupingBy(i -> atomicInteger.getAndIncrement() / size))
.values().forEach(i -> {
System.out.println(i.toString().replaceAll("\\[", "").replaceAll("]", ""));
});