首页 > 解决方案 > 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;
    }


}

标签: javavector

解决方案


If I see it correctly and you are just entering your name the problem is the scanning for int to get n. n is an int and the scanner will get your name which is a string which will result in the mismatch exception. Also v1 is unnecessary vector of objects as you know you are only giving it names, you should write the type name so you could later use the properties of Name.


推荐阅读