Java - Factor Generator program nextfactor method
I've been trying to modify the nextfactor method for a while now to get the desired result. Basically, I'm supposed to exclude all even numbers, except for 2 but am still unable to do it. The code for the class is below. Any help is appreciated. Regards
public class FactorGenerator
{
private int number;
public FactorGenerator(int num)
{
// initialise instance variables
number = num;
if (number <= 2) {
System.out.printl开发者_JS百科n("Wrong argument");
}
}
public boolean hasMoreFactors()
{
if (number >= 2) {
return true;
} else {
return false;
}
// return (number >= 2);
}
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;
if(number % nextFactor == 0)
while (! isDivisible(triedFactor)) {
triedFactor = triedFactor+1;
}
number = number / triedFactor;
return triedFactor;
}
}
Use
triedFactor = triedFactor==2 ? 3 : triedFactor+2;
instead of
triedFactor = triedFactor+1;
while (! isDivisible(triedFactor)) {
if(triedFactor == 2) {
triedFactor = triedFactor+1;
} else {
triedFactor = triedFactor+2;
}
}
Exclude all even except 2 ? This is code
public ArrayList GetExeptEven(int upperBound){
ArrayList list=new ArrayList();
list.add(1);
list.add(2);
for(int i=3;i<=upperBound;i=i+2)
list.add(i);
return list;
}
精彩评论