[英]Java - array list to output all factors
我被要求創建一個方法,將所有因子作為數組列表返回。 任何幫助都會受到贊賞,因為我已經被困了一段時間了。
/**
* 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();
}
}
而不是在這一行打印出來:
System.out.println(nextFactor());
創建一個ArrayList:
List<Integer> list = new ArrayList<Integer>();
並將它們存儲在其中:
list.add(nextFactor());
看起來你錯過了一個數字具有相同因子多次的情況。 例如,4 = 2 * 2,但是在嘗試了2之后,您增加並嘗試了下一個3。 您需要繼續嘗試每個候選人,直到不再成為一個因素為止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.