2

我是编程新手,我不确定这个我哪里出错了。

这是我的主要方法:

import java.util.*;
public class DisplayFactors
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a integer: ");
        String input1 = scan.nextLine();
        int input = Integer.parseInt(input1);

        FactorGenerator factor = new FactorGenerator(input);

        System.out.print(factor.getNextFactor());

        while (!factor.hasMoreFactors())
        {
            System.out.print(factor.getNextFactor());
        }
    }   
}

这是我的课:

public class FactorGenerator {

    private int num;
    private int nextFactor;

    public FactorGenerator(int n)
    {
        num = nextFactor = n;
    }

    public int getNextFactor()
    {
        int i = nextFactor - 1 ;

        while ((num % i) != 0)
        {
            i--;
        }
        nextFactor = i;
        return i;
    }

    public boolean hasMoreFactors()
    {
        if (nextFactor == 1)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

目前,如果我输入 15 作为整数,我只会得到一个因子,即 5,但我需要它来显示所有因子:15、5、3 和 1。我哪里出错了?

4

2 回答 2

4

当你使用

while (!factor.hasMoreFactors())
            {
                System.out.print(factor.getNextFactor());
            }

您说虽然没有更多的因子,但将它们打印在屏幕上,但只要因子存在于列表中,您就需要打印它们。

所以在Java中你将拥有:

while (factor.hasMoreFactors())
                {
                    System.out.print(factor.getNextFactor());
                }
于 2012-12-30T23:19:07.057 回答
1
while (!factor.hasMoreFactors())
{
    System.out.print(factor.getNextFactor());
}

一定是

while (factor.hasMoreFactors())
{
    System.out.print(factor.getNextFactor());
}
于 2012-12-30T23:13:29.470 回答