输出中的整数数量?简单的java程序

时间:2013-11-03 20:11:12

标签: java factors

我正在研究一个简单的java代码,它输出用户输入数字的所有因子。我如何计算然后显示输出的因子数?

System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();

System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
    if(d % w == 0){
        System.out.println(w);
    } 
} 

在上面的代码中,它是'w'中输出的整数的数量。例如,如果输入的数字是8且其因子是1,2,4,8,我该如何编写一个代码为'8 has 4个因素'?

由于

3 个答案:

答案 0 :(得分:3)

您只需要一个变量来计算因子:

System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
int nFactors = 0;

System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
    if(d % w == 0){
        System.out.println(w);
        ++nFactors;
    } 
}
System.out.println(d + " has " + nFactors + " factors");

答案 1 :(得分:0)

你需要一个计数器变量。这是代码:

int counter =0;

for(int w = 1; w <= d; w++ ){
        if(d % w == 0){
        counter++;   
        System.out.println(w);

        } 

System.out.println(d + " has " + counter + "factors ");

答案 2 :(得分:0)

尝试使用此代码:

import java.util.Scanner;

public class EmbalzadoFactorial {
    public static Scanner sc;

    public static void main(String[] args) {
        int Number, i;
        sc = new Scanner(System.in);

        System.out.print("Please Enter any number to Find Factors: ");
        Number = sc.nextInt();

      System.out.println("The factors are: ");
        for(i = 1; i <= Number; i++) {
            if(Number%i == 0) { 

                System.out.format(" %d  ", i);
            System.out.print ("and");
            System.out.format("%s %n ", i);
            }
        }
    }
}