Saturday, November 16, 2013

Java Vector class

Create a Person Class which contains two member variables firstName and lastName.Write a program that prompts the user to enter details of several persons.Model the collection of persons using Vector.

  • Print the vector containing person details.
  • Remove a person from vector and print.(Prompt the user to enter first name of the person to be deleted).
  • Insert a new person at some position entered by user.
  • Print details of first person.Replace it with “Harry Smith”
  • Convert the vector of Person objects to an array of Person objects.

SOLUTION: 

 
import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;

public class VectorClassExample {
 String fname;
 String lname;
 
 public static void main(String args[]) {
  //Prompting user for input
  System.out.println("Enter the number of people: ");
  //Creating Scanner object
  Scanner input = new Scanner(System.in);
  //Reading number of people
  int num = input.nextInt();
  //Allocating memory
  Vector v = new Vector();
  
  //Reading the first and last name.
  for ( int i = 0; i < num; i++ ) {
   System.out.printf("Enter %d user first name: ",i+1);
   String fname = input.next();
   System.out.printf("Enter %d user last name: ",i+1);
   String lname = input.next();
   
   //Storing the name to memory.
   v.add(fname+" " +lname);
  }
  
  //Creating iterator object.
  Iterator< VectorClassExample > it = v.iterator();
  //Displaying total users.
  System.out.println("Total available users");
  while ( it.hasNext() ) {
   System.out.println(it.next());
  }
  
  //Prompting for deletion of person.
  System.out.println("Enter first name to be delete");
  String h= input.next();
  System.out.println("Enter last name to be delete");
  String i= input.next();
  v.remove(h+" "+i);
  
  //Displaying total user.
  System.out.println("Total available users");
  Iterator< VectorClassExample > r = v.iterator();
  while ( r.hasNext() ) {
   System.out.println(r.next());
  }
  
  //Prompting for adding a new person.
  System.out.println("Enter the posion at which you want to add a user");
  int p=input.nextInt();
  System.out.println("Enter first name");
  String h1= input.next();
  System.out.println("Enter last name");
  String i1= input.next();
  v.add(p, (h1 + " " + i1) );
 
  //Displaying total user.
  System.out.println("Total available users");
  Iterator< VectorClassExample > sh = v.iterator();
  while ( sh.hasNext() ) {
   System.out.println(sh.next());
  }
  
  System.out.println ( v.elementAt(0) );
  v.set(0, ("harry"+" "+"smith") );
  System.out.println ( v.elementAt(0) );
  VectorClassExample pp[] =new VectorClassExample[num];
  v.toArray(pp);
 }
}

No comments:

Post a Comment