Assignment: JAVA
AIM: Write a menu driven Java program which will read a number and should
implement the following methods 1. factorial() 2. testArmstrong() 3.
testPalindrome() 4. testPrime() 5. fibonacciSeries()
PROGRAM:
package menujava;
import java.util.Scanner;
public class Main {
Scanner sc;
Main() {
sc = new Scanner(System.in);
}
void factorial() {
int num, fact;
fact = 1;
System.out.print("Enter a number to calculate factorial: ");
num = sc.nextInt();
for (int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println(num + "!" + " = " + fact);
}
void testArmstrong() {
int num, temp,n=0;
int sum = 0;
System.out.print("Enter a number to check if it is armstrong: ");
num = sc.nextInt();
temp = num;
while(temp % 10 != 0){
temp = temp / 10;
n++;
}
temp = num;
while (temp != 0) {
sum += (int) Math.pow(temp % 10, n);
temp /= 10;
}
System.out.println(num == sum ? num + " is an armstrong number" : num + "
is not an armstrong number");
}
void testPalindrome() {
int r,sum=0,temp;
System.out.print("Enter the no. to check pallindrome : ");
int n= sc.nextInt();//It is the number variable to be checked for palindrome
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
void testPrime() {
int num, ct;
ct = 0;
System.out.print("Enter a number to check if it is prime: ");
num = sc.nextInt();
for (int i = 1; i <= num; i++) {
if (num % i == 0)
ct++;
}
System.out.println(ct == 2 ? num + " is a prime number" : num + " is not a
prime number");
}
void fibonacciSeries() {
System.out.print("Enter the no. to find fibbonacci series : ");
int count =sc.nextInt();
int n1=0,n2=1,n3,i;
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i) {
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
public static void main(String[] args) {
Main obj = new Main();
Scanner sc = new Scanner(System.in);
int choice;
choice = 0;
do {
System.out.println("\n\tMenu");
System.out.println("1. Factorial of a number");
System.out.println("2. Test if a number is Armstrong");
System.out.println("3. Test if a number is Palindrome");
System.out.println("4. Test if a number is Prime");
System.out.println("5. Fibonacci series till a limit");
System.out.println("6. Exit");
System.out.print("Your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1: obj.factorial();
break;
case 2: obj.testArmstrong();
break;
case 3: obj.testPalindrome();
break;
case 4: obj.testPrime();
break;
case 5: obj.fibonacciSeries();
break;
case 6: System.out.println("\nExited Succesfully!");
break;
default: System.out.println("Wrong Choice, Please Try Again!");
}
} while (choice != 6);
}
}
OUTPUT:
Conclusion: In this way, we could implement a menu driven Java program which
will read a number and should implement the above methods.