All the menu driven program is coded using switch-case. We can write this type of programs in two way
1) Write the whole program in switch-case branches.
2) Create separate methods and call those methods from the switch-case branch.
Now we already explain the programs like prime no or palindrome no in our site although as this is different types of program, we write this again-
import java.util.*;
public class PrimeAndPalindrome
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
int ch,k;
while(true)
{
System.out.println("01. Prime no");
System.out.println("02. Palindrome no");
System.out.println("03. Quit");
System.out.print("Enter Your Choice : ");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.print("Enter A Number:");
k=sc.nextInt();
int d=2;
boolean b=true;
while(d<=k/2)
{
if(k%d==0)
{
b=false;
break;
}
d++;
}
if(b)
{
System.out.print(k + " is a prime Number");
}
else
{
System.out.print(k + " is not a prime Number");
}
break;
case 2:
System.out.print("Enter A Number:");
k=sc.nextInt();
int rev=0,temp=k;
while(temp>0)
{
rev = (rev*10) + (temp%10);
temp /= 10; // temp=temp/10
}
if(k==rev)
{
System.out.println(k + " is a palindrom No.");
}
else
{
System.out.println(k + " is not a palindrom No.");
}
break;
case 3:System.exit(0);
default: System.out.println("Wrong Entry");
}
}
}
}
Output
Enter Your Choice : 1
Enter A Number:31
31 is a prime Number
Enter Your Choice : 1
Enter A Number:32
32 is not a prime Number
Enter Your Choice : 2
Enter A Number:121
121 is a palindrom No.
Enter Your Choice : 2
Enter A Number:122
122 is not a palindrom No.
Enter Your Choice : 3