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 %(x/y/z/a/b/c)f
will print strings/ints/doubles/etc. Right justified with spacing based on the x/y/z/a/b/c
, 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(System.in);
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 = sc.next();
if (yesno.equalsIgnoreCase("y"))
{
for(increment=incvalue; increment<(max+incvalue); increment=increment+incvalue)
System.out.println(increment);
}
else if (yesno.equalsIgnoreCase("n"))
{
for (increment=incvalue; increment<(max+incvalue); increment=increment+incvalue)
System.out.print(increment + ". ");
}
else
System.out.print("");
}
}
Here's the code I have so far.
This is a relatively simple use of the %
operator:
for (increment = incvalue; increment < max + incvalue; increment += incvalue) {
System.out.print(increment);
if (increment % (incvalue * 6) == 0)
System.out.println();
}