5
\$\begingroup\$

Displaying Some Multiples Write a program to calculate the multiples of a given number. Have the user enter a number, and then use a for loop to display all the multiples of that number from 1 to 12. It is not necessary to use a function. You must use a for loop.

/*
 * Code by Clint <https://github.com/clieg>
 *
 *
 * Problem from: http://programmingbydoing.com/a/displaying-some-multiples.html
 */

import java.util.Scanner;

public class DisplayingSomeMultiples {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int number;

        System.out.print("Choose a number: ");
        number = input.nextInt();

        System.out.println();

        for (int i = 1; i <= 12; i++) {
            int mutiply = number * i;
            System.out.println(number + " x " + i + " = " + mutiply);
        }
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ multiple instead of mutiply will get you one point more. ;) \$\endgroup\$
    – Joop Eggen
    Sep 21 '20 at 8:18
  • \$\begingroup\$ @JoopEggen or removing the temporary variable entirely... \$\endgroup\$
    – slepic
    Sep 21 '20 at 10:00
  • \$\begingroup\$ Strictly speaking, your program outputs much more then what it is supposed to ;) \$\endgroup\$
    – slepic
    Sep 21 '20 at 10:03
2
\$\begingroup\$

That looks quite good actually, minor stuff only.


for (int i = 1; i <= 12; i++) {

I'm a persistent advocate for using "real" names for loop variables, like index or count or factor in this case.

        for (int factor = 1; factor <= 12; factor++) {
            int result = number * factor;
            System.out.println(number + " x " + factor + " = " + result);
        }

        Scanner input = new Scanner(System.in);
        int number;

Do not declare all variables at the beginning of the method, declare them only when needed, that will limit the variable from creeping into scopes they don't belong in.


You could define the maximum factor as a constant.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy