SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:9 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.