Program to demonstrate a menu‐driven class to accept a number from the user and check whether it is a Perfect number or not in Java.
Perfect number – a number is called a Perfect number if it is equal to the sum of its factors other
than the number itself. Example: 6 = 1 + 2 + 3.
Perfect number – a number is called a Perfect number if it is equal to the sum of its factors other
than the number itself. Example: 6 = 1 + 2 + 3.
package com.hubberspot.java.example;
import java.util.Scanner;
public class PerfectNumberTest {
public static void main(String[] args) {
char program;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Press 'P' for Perfect Number Test or 'E' for Exit");
program = scanner.nextLine().toUpperCase().charAt(0);
if(program != 'P' && program != 'E') {
System.out.println();
System.out.println("You entered : " + program);
System.out.println("Please enter P or E to proceed ... try again");
System.out.println();
continue;
}
else {
switch( program )
{
case 'P':
System.out.print( "Enter number for Perfect Number checking: " );
int number = scanner.nextInt();
String line = scanner.nextLine();
if( isPerfectNumber( number ) )
{
System.out.println( number + " is a perfect number." );
}
else
{
System.out.println( number + " is not a perfect number." );
}
break;
}
}
System.out.println();
if( program == 'E') {
System.out.println("Exiting from the program...");
}
}
while(program != 'E');
}
private static boolean isPerfectNumber(int number) {
int sumOfFactors = 0;
for( int i = 1; i < number; i++ )
{
if( (number % i ) == 0 )
{
sumOfFactors = sumOfFactors + i;
}
}
return( sumOfFactors == number );
}
}
Output of the program :
