Friday 10 January 2020

Menu Driven Java Program for Voter Management System

Q11 The election commission requires the following task to be done. A class Voter with ID, name, age and address as fields. Write toString(), getter methods and setData() method. The VoterDemo has main() method which reads and stores data of 10 voters and displays a menu with following operations: 
a) Add new voter 
b) Search voter based on ID 
c) Search voter whose name starts with “A” 
solution: 
package p2; 

public class Voter  
{ 
private long id; 
private String name,address; 
private int age; 
public void setData(long id, String name,int age,String address) 
{ 
this.id=id; 
this.name=name; 
this.age=age; 
this.address=address; 
} 
public String toString() 
{ 
return "Voter id = "+id+" Voter Name =" +name+" Voter age =" +age+"\n Address = "+address; 
} 
public long getId() 
{ 
return id; 
} 
public String getName() 
{ 
return name; 
} 
} 
package p2; 

import java.util.Scanner; 

public class VoterDemo  
{ 
public static int linearSearch(Voter v[],int n,long key) 
{ 
for(int i=0;i<n;i++) 
{ 
if(v[i].getId()==key) 
return i; 
} 
return -1; 
} 
public static void linearSearch(Voter v[],int n) 
{ 
int flag=0; 
for(int i=0;i<n;i++) 
{ 
if(v[i].getName().charAt(0) == 'A') 
{ 
flag=1; 
System.out.println(v[i]); 
} 
} 
if(flag ==0) 
System.out.println("no voter whose name starts with A"); 
} 
public static void main(String[] args 
{ 
Voter v[]=new Voter[10]; 
Scanner sc = new Scanner(System.in); 
int choice,nov=0,index; 
while(true) 
{ 
System.out.println("Menu");  
System.out.println("1. Add new voter"); 
System.out.println("2. Search voter based on ID"); 
System.out.println("3. Search voter whose name starts with 'A'"); 
System.out.println("4. exit"); 
choice =sc.nextInt(); 
switch(choice) 
{ 
case 1: 
v[nov]=new Voter(); 
System.out.println("Enter id, name, age and address of voter"); 
long id=sc.nextLong(); 
sc.nextLine(); 
String name=sc.nextLine(); 
int age=sc.nextInt(); 
sc.nextLine(); 
String address=sc.nextLine(); 
v[nov].setData(id,name,age,address); 
nov++; 
break; 
case 2: 
System.out.println("enter the id of voter"); 
long key=sc.nextLong(); 
index=linearSearch(v,nov,key); 
if(index != -1) 
{ 
System.out.println("voter details are"); 
System.out.println(v[index]); 
} 
else 
System.out.println("Search id not found"); 

break; 
case 3: 
linearSearch(v,nov); 
break; 
case 4: 
System.exit(0); 

} 
} 
} 

} 

No comments:

Post a Comment