Search code examples
javaintfactorization

How to avoid returning a zero


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?


Solution

  • 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.