Java-用于输出所有因子的数组列表
我被要求创建一个方法,将所有因子作为数组列表返回。任何帮助都将不胜感激,因为我已经被困了一段时间了Java-用于输出所有因子的数组列表,java,Java,我被要求创建一个方法,将所有因子作为数组列表返回。任何帮助都将不胜感激,因为我已经被困了一段时间了 /** * Determines whether the number has factors. * * @return true iff the number has a factor */ public boolean hasMoreFactors() { if (number >= 2) { return true; } else {
/**
* 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>();
它看起来像是你错过了什么——一个数字多次具有相同的因子。例如,4=2*2,但在尝试2之后,将递增,然后再尝试3。您需要不断尝试每一位候选人,直到它不再是一个因素。阅读本文可能会有所帮助:。它的特点是
还有一个简单的Java实现检查。请您详细说明一下,您是如何陷入困境的首先,返回布尔表达式而不是将其包装在if中。同意返回一个列表而不是只系统输出每个因子更可取。然而,我认为OPs最主要的关注点是获得正确的结果。忘记添加类等in@RayOP的问题是关于返回Arraylist。OP没有提到任何关于算法本身的问题。
list.add(nextFactor());