Reputation: 135
I've been asked to create a method that returns all of the factors as an array list. Any help would be appreciated as I've been stuck for some while now.
/**
* 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();
}
}
Upvotes: -1
Views: 3196
Reputation: 4869
It looks like what you missed it the case where a number has the same factor multiple times. For example, 4 = 2 * 2, but after you've tried 2, you increment and try 3 next. You need to keep trying each candidate until it is no longer a factor.
Upvotes: 0
Reputation: 274650
Instead of printing them out in this line:
System.out.println(nextFactor());
create an ArrayList:
List<Integer> list = new ArrayList<Integer>();
and store them in it:
list.add(nextFactor());
Upvotes: 1