Write a method called printFactors that accepts an integer as its parameter and uses a fencepost loop to print the factors of that number, separated by the word "and". For example, the factors of the number 24 should print as the following:
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
You may assume that the parameter’s value is greater than 0, or you may throw an exception if it is 0 or negative.
Your method should print nothing if the empty string ("") is passed.
package indefinite_loops;
import java.util.Scanner;
public class PrintFactors {
public void printFactors() {
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = input.nextInt();
// make sure while loop takes only numbers greater than zero
while(!(number>0)) {
System.out.print("Please enter value greater than zero: ");
number = input.nextInt();
}
System.out.print(1);
// loop over all the numbers and check if they perfectly divide the number
for (int i = 2; i < number; i++) {
if (number % i == 0) {
// print those numbers
System.out.print( " and " + i);
}
}
System.out.println(" and " +number);
}
public static void main(String[] args) {
PrintFactors factors = new PrintFactors();
factors.printFactors();
}
}
Output:
Enter a positive integer: -6
Please enter value greater than zero: 0
Please enter value greater than zero: 99
1 and 3 and 9 and 11 and 33 and 99