Skip to content
Advertisement

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 a InputMismatchException exception.

Here is 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;
    }


}

Advertisement

Answer

Your problem is not with vector, it is with scanner methods; you can read this answer, it will give you a good idea about how to use scanner methods.

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");
}
}
Advertisement