2011-02-01 52 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。你需要不斷嘗試每個候選人,直到它不再是一個因素。