Thursday, January 12, 2012

Menu Driven BlueJ Program on Odd, Even and Perfect Numbers


The question here is that,  Write a BlueJ program which will ask the user to enter a choice and based on the choice the following operation will take place.
if choice=1; then sum of even nos. from the series of 10 nos.
if choice=2; then sum of odd nos. from a series of 10 nos.
if choice=3; then it will check whether the no is perfect or not from a series of 10 nos.

Codes of the Menu driven BlueJ Program

import java.io.*;
class Menu
{
  BufferedReader br;
int arr[]=new int[10];
   public static void main(String args[])throws IOException
   {
  Menu ob=new Menu ();
 ob.accept();
   }
  Menu ()
  {
   br=new BufferedReader(new InputStreamReader(System.in));
  }
public void accept()throws IOException
{
int choice;
for(int i=0;i<10;i++)
{
 System.out.println("Enter number:");
 arr[i]=Integer.parseInt(br.readLine().trim());
}
System.out.println("Enter Your Choice (1 for adding even numbers, 2 for adding odd number and 3 for checking perfect number:");
 choice=Integer.parseInt(br.readLine().trim());
if(choice==1)
addEven();
else if(choice==2)
addOdd();
else if(choice==3)
showPerfect();
else
System.out.println("Wrong Choice:");
}
private void addEven()
{
 int sum=0;
 for(int i=0;i<10;i++)
 {
     if(arr[i]%2==0)
     sum=sum+arr[i];
    }
    System.out.println("Sum of Even Numbers="+sum);
}

private void addOdd()
{
 int sum=0;
 for(int i=0;i< 10;i++)
 {
     if(arr[i]%2!=0)
     sum=sum+arr[i];
    }
    System.out.println("Sum of Odd Numbers="+sum);
}
private void showPerfect()
{
 int sum;
 for(int i=0;i<10;i++)
 {
     sum=0;
  for(int j=1;j< arr[i];j++)
 {
     if(arr[i]%j==0)
     sum=sum+j;
    }
    if(sum==arr[i])
    System.out.println(arr[i]+ " is a Prefect Number");
}
}
}


Sample input and output of the BlueJ program

Enter number:
22
Enter number:
4
Enter number:
35
Enter number:
4
Enter number:
32
Enter number:
12
Enter number:
6
Enter number:
5
Enter number:
4
Enter number:
33
Enter Your Choice (1 for adding even numbers, 2 for adding odd number and 3 for checking perfect number:
3
6 is a Prefect Numbers
Enter number:
2
Enter number:
4
Enter number:
33
Enter number:
6
Enter number:
5
Enter number:
45
Enter number:
7
Enter number:
12
Enter number:
2
Enter number:
3
Enter Your Choice (1 for adding even numbers, 2 for adding odd number and 3 for checking perfect number:
1
Sum of Even Numbers=26

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner