构造函数和数组不工作,String to String []

时间:2017-05-11 15:09:00

标签: java arrays string testing constructor

我现在正在努力弄清楚为什么在尝试测试时我无法对构造函数输入任何兴趣,并收到String无法转换为String []的错误。如果你能确定我出错的地方,那将对我有很大的帮助。

public class ProfileMain {

public static void main(String[] args) {
    Profile profile1;
    profile1 = new Profile("name" , "town" , "country", "nationality", "dateOfBirth", "socks" );
    System.out.println(profile1.toString());
}
}

    public Profile (String name, String town, String country, String nationality, String dateOfBirth, String [] interests) { 

    this.name = name;
    this.town = town;
    this.country = country;
    this.nationality = nationality;
    this.dateOfBirth = dateOfBirth;
    this.interests = interests;

}    

2 个答案:

答案 0 :(得分:1)

String[]String是两回事。

String[]String个实例的数组,StringString类的实例,定义为String str="hello"

1.两个构造函数和new运算符应该具有相同的类型。 如果兴趣是最后一个字段可以多次出现,则可以使用var arg。

public class Profile {
    private String name;
    private String town;
    private String country;
    private String nationality;
    private String dateOfBirth;
    private String[] interests;

    Profile (String name, String town, String country, String nationality, String dateOfBirth, String ... interests) { 
        this.name = name;
        this.town = town;
        this.country = country;
        this.nationality = nationality;
        this.dateOfBirth = dateOfBirth;
        this.interests = interests;
    }
}

答案 1 :(得分:0)

[]构造函数中的interests之后添加Profile,例如

public Profile (String name, String town, String country, String nationality, 
                String dateOfBirth, String interests[]) { // --> here

StringString[]不是一回事。当你这样做

this.interests = interests;

this.interestString[]interestString。因此,错误。

但是,您将socks作为interest传递,这是String而不是String[]。如果您只需要一个兴趣,请将String interests []=new String [10];改为String interest

但是,如果您需要多个兴趣,则传递数组,而不是"socks"