-2

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+",");
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
revl
  • 3
  • 6

3 Answers3

1

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.

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
  • 1
    This will print `0` on the first line, then immediately print `\n`. Change the newline condition to `i % 6 == 5`. – Bucket Oct 08 '18 at 18:32
1

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;
    }
}
Feedforward
  • 4,521
  • 4
  • 22
  • 34
revl
  • 3
  • 6
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("]", ""));
        });
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56