本文介绍了Java - Factor Generator程序nextfactor方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试修改nextfactor方法一段时间以获得所需的结果。基本上,我应该排除所有偶数,除了2但我仍然无法做到。该课程的代码如下。任何帮助表示赞赏。问候

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.println("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;
}
        }


推荐答案

while (! isDivisible(triedFactor)) {
    if(triedFactor == 2) {
      triedFactor = triedFactor+1;
    } else {
      triedFactor = triedFactor+2;
    }
} 

这篇关于Java - Factor Generator程序nextfactor方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 10:44