2011-02-01 50 views
0

我被要求创建一个方法,将所有因子作为数组列表返回。任何帮助将不胜感激,因为我一直坚持一段时间了。Java - 用于输出所有因子的数组列表

/** 
* Determines whether the number has factors. 
* 
* @return true iff the number has a factor 
*/ 
public boolean hasMoreFactors() 
{ 
    if (number >= 2) { 
     return true; 
    } else { 
     return false; 
    } 
    // return (number >= 2); 
} 

/** 
* Is number divisible by a given other number? 
* 
* @param otherNumber the number we test whether it divides the object's number 
* @return true iff the number is divisible by otherNumber 
*/ 
public boolean isDivisible(int otherNumber) 
{ 
    if (number % otherNumber == 0) { 
     return true; 
    } else { 
     return false; 
    } 
} 

/** 
* Determine next factor. 
* pre-condition: call only if hasMoreFactors 
* returns true 
* 
* @return a factor of the object's number 
*/ 
public int nextFactor() 
{ 
    int triedFactor = 2; 
    while (! isDivisible(triedFactor)) { 
     triedFactor = triedFactor+1; 

    } 
    number = number/triedFactor; 
    return triedFactor; 
} 

/** 
* Print all factors of the generator's number on standard output. 
*/ 
public void printAllFactors() 
{ 
    System.out.println("Factors of " + number); 
    while (hasMoreFactors()) { 
     System.out.println(nextFactor()); 
    } 
    System.out.println("That's it."); 
} 

/** 
* Main method: Read an integer and print all its factors. 
*/ 
public static void main(String[] args) 
{ 
    System.out.print("Please enter a number greater or equal 2: "); 
    Scanner sc = new Scanner(System.in); 
    int num = sc.nextInt(); 
    System.out.println(); 
    FactorGenerator gen = new FactorGenerator(num); 
    gen.printAllFactors(); 
} 

}

+0

请您详细说明一下,你怎么卡住了? :D – Skurmedel 2011-02-01 14:06:38

+0

首先,只是`返回BooleanExpression;`而不是将其包装在if中。 – unholysampler 2011-02-01 14:09:43

回答

1

,而不是打印出来这行:

System.out.println(nextFactor()); 

创建一个ArrayList:

List<Integer> list = new ArrayList<Integer>(); 

并将其存储在它:

list.add(nextFactor()); 
0

它看起来像你错过了一个数字具有相同因子多次的情况。例如,4 = 2 * 2,但在尝试2之后,您将增加并尝试3。你需要不断尝试每个候选人,直到它不再是一个因素。