Search This Blog

Sunday 27 April 2014

Java program to create a vector and add elements at appropriate locations.

import java.util.*;
import java.io.*;
import java.lang.String;

class Vector1
{
    public static void main(String args[])
    {
        try
        {
       
            int length = args.length;
            int i,ch;
            String str1,str2;

            Vector list = new Vector();

            for( i=0;i<length;i++)
            {
                list.addElement(args[i]);
            }

            DataInputStream in= new DataInputStream(System.in);
           
            for(;;)
            {
                System.out.println("1.Add element at end");
                System.out.println("2.Add element at specific location");
                System.out.println("3.Display");
                System.out.println("4.Exit");       
                System.out.println("Enter your choice:");
   
                str1=in.readLine();
                ch=Integer.parseInt(str1);

                switch(ch)
                {
                   
                    case 1: System.out.print("Enter an element to insert at end:");
                            str2=in.readLine();
                            list.addElement(str2);
                            length++;   
                            for(i=0;i<length;i++)
                            System.out.println(list.elementAt(i));
                            break;
                       
                    case 2: System.out.print("Enter an element & position:");
                            str1=in.readLine();
                            str2=in.readLine();
                            int pos;
                            pos=Integer.parseInt(str2);
                            if(pos<=length && pos>0)
                            {
                                list.insertElementAt(str1,pos-1);
                                length++;
                                for(i=0;i<length;i++)
                                    System.out.println(list.elementAt(i));
                                break;
                            }
                            else
                            {
                                System.out.println("Invalid Position!");
                            }
                   
                    case 3:
                            System.out.println("List of elements:");
                            for(i=0;i<length;i++)
                            System.out.println(list.elementAt(i));
                            break;
                   
                    default:System.exit(0);
   
                }
                              
            }
        }
        catch(Exception e){}
    }
}

No comments :

Post a Comment

FREE Hit Counters