How to avoid returning a zero

91 views Asked by At

I have got the code working, it is a prime factorization method class and tester. It prints out the code fine but I am forced to return a zero value, because the method is an Integer method.

public class FactorGenerator{
private int num;

public FactorGenerator(int numberToFactor){
    num = numberToFactor;
}
public int nextFactor(){
    for(int i = 2; i <= num;){
        if (num%i==0){
            num = num/i;
            System.out.println(i);
        }
        else{
            i++;
        }
    }
return 0;
}
public boolean hasMoreFactors(){
    for(int i = 1; i < num; i++){
        if(num % i == 0){
            return true;
        }
    }
    return false;
    }
}

And this is the tester I am using, which cannot be changed, and must stay the same:

import java.util.Scanner;

 public class FactorPrinter{
  public static void main(String [] args){

    Scanner in = new Scanner(System.in);
    System.out.print("Enter a number to Factor:");
    int numberToFactor = in.nextInt();

    System.out.println("You chose: "+numberToFactor+" to factor.");

    FactorGenerator fg = new FactorGenerator(numberToFactor);

    while (fg.hasMoreFactors())
        System.out.println(fg.nextFactor());
  }
 }

When I input 150, it prints 2,3,5,5,0 Is there anyway to remove the 0?

3

There are 3 answers

2
John Kugelman On BEST ANSWER

Don't print the factors in nextFactor(). Return them.

public int nextFactor() {
    for (int i = 2; ; i++) {
        if (num % i == 0) {
            num /= i;
            //System.out.println(i);
            return i;
        }
    }
}

The test num % i == 0 is guaranteed to return true eventually, so if you remove the i <= num test from the for loop the compiler won't require you to add return 0 at the end.

2
Jean-François Fabre On

All required prints are done in nextFactor. So just don't print the return code. Change this:

System.out.println(fg.nextFactor());

by this:

fg.nextFactor();

That said, the nextFactor name is then ill-named. Even if it yields the result, the name suggests that it's a generator which should return each factor at each call, the memory effect being provided by the num member method. So doing what I'm advising works, but it may not be in the spirit of the problem. John's answer would be better if you have to examine/store the factors, not only print them.

0
leeyuiwah On

Your hasMoreFactor() method should have returned false by the time it has been invoked four times (and nextFactor returned 2, 3, 5, 5, respectively) and is invoked the fifth time.