How do I add two string elements in vector?

I am new to java and learning through a task.

I have tried to create a program but when I input my name it is raising exception: InputMismatchException

Please have a look at my code.

Name.java

package LearnJava;

public class Name {
    String firstName,surName;

    public Name(String fName, String sName) {
        super();
        this.firstName = fName;
        this.surName = sName;
    }

    public String getName() {
        return firstName;
    }

    public void setName(String fName) {
        this.firstName = fName;
    }

    public String getSname() {
        return surName;
    }

    public void setSname(String sName) {
        this.surName = sName;
    }


}

Answer

Your problem is not with vector , it is with scanner methods , you can see this answer it will give you a good idea about how to use scanner methods : Scanner is skipping nextLine() after using next() or nextFoo()?

That’s because the Scanner.nextInt method does not read the newline character in your input created by hitting “Enter,” and so the call to Scanner.nextLine returns after reading that newline. You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself).

your code working:

 public class Main {
 public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    System.out.println("enter the choice:");
    System.out.println("n1.Accept first name and surnamen2.display total namen3.Exit.");
    int choice=Integer.parseInt(sc.nextLine());
    Vector v1=new Vector ();
    Vector<Name> v2=new Vector<Name>();

    while(choice !=3)
    {
        if(choice==1)
        {
            System.out.println("enter number of persons :");
            int n=Integer.parseInt(sc.nextLine());
            for(int i=1;i<=n;i++)
            {
                System.out.println("enter the first name of person number :"+(i));
                String fn =sc.nextLine();
                System.out.println("enter the last name of person number :"+(i));
                String ln =sc.nextLine();
                 v1.add( new Name( fn, ln));
            }
        }
        System.out.println("nn Enter the choice:");
        System.out.println("n1.Accept first name and surnamen n2.display total namen3.Exit.");
                choice=Integer.parseInt(sc.nextLine());
        if(choice==2)
        {
            System.out.println("n ********************** Here is total:"+v1.size()+"nn");
        }
    }
    System.out.println("thank you");
}
}