如何使用循环打印输入因子?

时间:2017-03-16 11:02:11

标签: java loops factors

这是我的代码混乱。我必须编写一个输入大于3的正整数的程序。验证整数实际上是否大于3.然后打印所有可能的正整数对,这些正整数大于其乘积小于或等于输入的数。

ex. If 24 is the input.
It would print:
4 = 2 x 2 
6 = 2 x 3
8 = 2 x 4
10 = 2 x 5
12 = 2 x 6
14 = 2 x 7
16 = 2 x 8....
9 = 3 x 3
12 = 3 x 4..
24 = 3 x 8...
all the way to 
24 = 4 x 6

import java.util.Scanner;

public class Factors {
    public static void main(String[] args) {
        // Define Variables
        Scanner input = new Scanner(System.in);
        int i = 0;
        int j = 0;
        int k = 2;
        int product = 0;
        // Ask for input/loop
        while (i < 3) {
            System.out.println("Please enter an integer greater than 3");
            i = input.nextInt();
        }
        while (product < i) {
            if (product == i) { j++; k = 2; 
        for (j = 2; product < i; k++) {
                product = j * k;
                System.out.println(product + " = " + j + " x " + k);
                if (product == i) { j++; k = 2; 
                }   
            }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

public class Factors {
public static void main(String[] args) {
    // Define Variables
    Scanner input = new Scanner(System.in);
    int i = 0;
    int product = 0;
    // Ask for input/loop
    while (i < 3) {
        System.out.println("Please enter an integer greater than 3");
        i = input.nextInt();
    }
    for (int j = 2; j < i / 2; j++) {
        for (int k = 2; k < i / 2; k++) {
            if (j <= k && j * k <= i)
                System.out.println(j * k + " = " + j + "*" + k);
        }
    }
    // while (product < i) {
    // if (product == i) {
    // j++;
    // k = 2;
    // for (j = 2; product < i; k++) {
    // product = j * k;
    // System.out.println(product + " = " + j + " x " + k);
    // if (product == i) {
    // j++;
    // k = 2;
    // }
    // }
    // }
    // }
}

}