我被要求创建一个方法,将所有因子作为数组列表返回。任何帮助将不胜感激,因为我一直坚持一段时间了。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();
}
}
请您详细说明一下,你怎么卡住了? :D – Skurmedel 2011-02-01 14:06:38
首先,只是`返回BooleanExpression;`而不是将其包装在if中。 – unholysampler 2011-02-01 14:09:43