Exception of a specific integer from java return method

I am just starting java and have written a simple program to return input factors. There are two classes, the tester and the one you see below.

Unfortunately, my conclusion, say, if I entered 150, is 2, 3, 0, 5, 5.

I know why this is happening; when the local variable q = i, we obviously get 2, 3, 5, 5, but when the condition in the first condition, if is not satisfied, q is read as 0.

Is there a way to exclude a specific integer, in this case 0, from the output? I struggled with what should be a simple problem for several hours, so obviously I don't see anything.

I understand that there are easier ways to write this program, but all methods should remain the same as ...

public class FactorGenerator {

    private int y;
    private int i;


    public FactorGenerator(int numberToFactor)
    {
        y = numberToFactor;
        i = 2;
    }

    public boolean hasMoreFactors()
    {
        if (i <= y)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int nextFactor()
    {

        int q=0;

        if( y % i != 0)
            i++;

        if( y % i == 0)
            {
                y = y / i;
                q = i;
            }           
        return q;
    }   
}
+4
2

. while ( , y) :

if( y % i != 0)
        i++;

:

while( y % i != 0){
        i++;
}
+1

@MicD

:

, , q

    int nextFactor()
{

    int q=0;

    if( y % i != 0)
        i++;

    if( y % i == 0)
        {
            y = y / i;
            q = i;
        }
    if(q!=0)
        return q;
    else
        nextFactor();
}
+1

Source: https://habr.com/ru/post/1670368/


All Articles