-1

I'm trying to format the output of a multiplication table where you can only have 5 numbers/integers on one line. I'm trying this using a printf method in a for loop but it's not working so far.

Code:

System.out.println("Which multiplication table do you want to print?: ");
int number = input.nextInt();
int calculation;
System.out.println("Multiplication table: " + number + ":");
for (int i = 1; i <= 10; i++ ) {
    calculation = number * i;
    System.out.printf("%-5s ", calculation);
}

My output:

3    6    9    12   15   18   21   24   27   30  

Output I'm trying to get:

 3    6    9    12   15
 18   21   24   27   30 
itsmysterybox
  • 2,748
  • 3
  • 21
  • 26

3 Answers3

2

Print a line breaker every 5 number:

calculation = number * i;
System.out.printf("%-5s ", calculation);
if (i % 5 == 0) {
   System.out.println();
}    
xingbin
  • 27,410
  • 9
  • 53
  • 103
1

Print a newline after printing 5 elements:

if(i % 5 == 0)
   System.out.println();
Mushif Ali Nawaz
  • 3,707
  • 3
  • 18
  • 31
1

I think you have multiple options to achieve this: 1. Print a new empty line after the 5th iteraiton 2. Add "\n" to mark end of line

1.

for (int i = 1; i <= 10; i++ ) {
        calculation = number * i;
        if (i % 5 == 0) {
         System.out.println();
        }    
        System.out.printf("%-5s ", calculation);
}

2.

for (int i = 1; i <= 10; i++ ) {
        calculation = number * i;
        if (i % 5 == 0) {
         System.out.printf("\n");
        }    
        System.out.printf("%-5s ", calculation);
}

Hope this helps

JWiryo
  • 371
  • 4
  • 11
  • One more question, what exactly is the "%" operator used for and when is it used for most of the time(examples please)? – Configuration Sep 27 '18 at 12:55
  • Ah, sorry for not explaining that. % is a _modulus_ operator in Java or modulo in Python (if im not mistaken) but they are exactly the same thing. Essentially, it is a division operation but instead of returning the _quotient_ value it returns the remainder. ` x % 5 == 0 ` is an expression to check whether x is completely divisible by 5 as the remainder of that division operation is 0. This is explained well here https://stackoverflow.com/questions/17524673/understanding-the-modulus-operator Hope this helps – JWiryo Sep 28 '18 at 02:56