Ronan Ronan - 1 year ago 87
Java Question

Outputting/printing 6 numbers per line from a loop

I'm trying to write a very basic code that takes takes a number (done by manually editing the code (i.e. no scanner allowed) and then prints all of it's multiples up to a certain max (also something imputed manually in the code). I have the code working for the loops, values, etc. - it's just that we have to include 2 ways to print it. One way is easy, with each number on a new line. The other way is much harder - each line has 6 numbers, right intended, separated by a few spaces. I know that

will print strings/ints/doubles/etc. Right justified with spacing based on the
, but I don't know how to automatically start a new line after 6 numbers.

import java.util.*;
public class IncrementMax
public static void main(String[] args)
Scanner sc = new Scanner(;

int maxvalue = 200; // these top 2 values have to be adjusted to suit the program to your needs
int incvalue = 5;
int increment = incvalue;
int max = 200;

System.out.println("I will print the multiples of " + increment + ", up to " + max + ". Do you want each number on a different line (y/n)?");
String yesno =;

if (yesno.equalsIgnoreCase("y"))
for(increment=incvalue; increment<(max+incvalue); increment=increment+incvalue)
else if (yesno.equalsIgnoreCase("n"))
for (increment=incvalue; increment<(max+incvalue); increment=increment+incvalue)
System.out.print(increment + ". ");

Here's the code I have so far.

Answer Source

This is a relatively simple use of the % operator:

for (increment = incvalue; increment < max + incvalue; increment += incvalue) {
    if (increment % (incvalue * 6) == 0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download