//import the Scanner class to allow for user's input
import java.util.Scanner;
//Declare the class and call it FactorClass
public class FactorClass {
//Declare the function factor
//It returns either true or false, therefore the return type is boolean
//It receives two arguments - a and b
public static boolean factor(int a, int b){
//Check if a is divisible by b.
//Return true if yes
if(a % b == 0){
return true;
}
//return false if a is not divisible by b
return false;
} // End of method factor
//The main method to test the function factor()
public static void main(String[] args) {
//Create an object of the Scanner class
Scanner input = new Scanner(System.in);
//Prompt the user to enter the pair of numbers
System.out.println("Enter the pair of numbers (separated by a space)");
//grab and store the first number in a variable
int firstnum = input.nextInt();
//grab and store the second number in another variable
int secondnum = input.nextInt();
//With the variables, call the factor() method
//If it returns true, print the adequate message
if(factor(firstnum, secondnum)){
System.out.println(secondnum + " is a factor of " + firstnum);
}
//If it returns false, print the adequate message
else{
System.out.println(secondnum + " is NOT a factor of " + firstnum);
}
} // End of main method
} // End of class declaration
==============================================================
<h2>Sample Output 1:</h2>>> Enter the pair of numbers separated by a space
8 4
>> 4 is a factor of 8
==============================================================
<h2>Sample Output 2:</h2>>> Enter the pair of numbers separated by a space
9 4
>> 4 is NOT a factor of 9
==============================================================
<h2>Explanation:</h2>
The above code has been written in Java and it contains comments explaining every segment of the code. Kindly go through the comments for better understanding of the code.
For simplicity, the code is re-written as follows with little or no comments;
import java.util.Scanner;
//Declare the class and call it FactorClass
public class FactorClass {
public static boolean factor(int a, int b) {
if(a % b == 0){
return true;
}
//return false if a is not divisible by b
return false;
} // End of method factor
//The main method to test the function factor()
public static void main(String[] args) {
//Create an object of the Scanner class
Scanner input = new Scanner(System.in);
//Prompt the user to enter the pair of numbers
System.out.println("Enter the pair of numbers (separated by a space)");
//grab and store the first number in a variable
int firstnum = input.nextInt();
//grab and store the second number in another variable
int secondnum = input.nextInt();
if(factor(firstnum, secondnum)){
System.out.println(secondnum + " is a factor of " + firstnum);
}
else{
System.out.println(secondnum + " is NOT a factor of " + firstnum);
}
}
}