Java 构造函数和数组不工作,字符串到字符串[]
我现在正在努力弄清楚为什么在测试构造函数时不能将任何兴趣输入到构造函数中,并收到一个错误,即字符串不能转换为字符串[]。如果你能找出我哪里出了问题,那将对我大有帮助Java 构造函数和数组不工作,字符串到字符串[],java,arrays,string,testing,constructor,Java,Arrays,String,Testing,Constructor,我现在正在努力弄清楚为什么在测试构造函数时不能将任何兴趣输入到构造函数中,并收到一个错误,即字符串不能转换为字符串[]。如果你能找出我哪里出了问题,那将对我大有帮助 public class ProfileMain { public static void main(String[] args) { Profile profile1; profile1 = new Profile("name" , "town" , "country", "nationality", "date
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;
}
在您的配置文件构造函数中
public Profile(... ... String dateOfBirth, String interests) {
...
this.interests = interests;
}
兴趣对象是数组,因此参数也必须是数组:
String[] interests
在
配置文件
构造函数中的兴趣
之后添加[]
,如
public Profile (String name, String town, String country, String nationality,
String dateOfBirth, String interests[]) { // --> here
String
和String[]
不是一回事。当你这样做的时候
this.interests = interests;
this.interest
是一个字符串[]
,interest
是一个字符串。因此,这是一个错误
但是,您可以将socks
作为interest
传递,它是字符串
,而不是字符串[]
。如果您只需要一个兴趣,那么将String interests[]=newstring[10]编码>到字符串兴趣中
但是,如果您需要多个兴趣,则传递一个数组,而不是“socks”
,您在此处将兴趣声明为数组:
String interests []=new String [10];
然后你试图将一个字符串赋予同样的兴趣
declare interests具有普通字符串,或者在构造函数中执行以下操作:
String[] interests
您正在传递一个字符串作为方法“Profile”的参数“interests”,而不是字符串数组
将兴趣设置为字符串或传递字符串数组。string[]
和string
是两件不同的事情
String[]
是String
实例的数组,String
是String
类的实例,定义为String str=“hello”
1.构造函数和新运算符应具有相同的类型。
如果感兴趣,则可以使用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;
}
}
嗯,是的,String
和String[]
是不同的类型,你不能简单地将一个指定给另一个,就像你可以将一个Integer
对象指定给String[]
变量一样。我如何传递数组?我不确定是否需要添加一个字符串,所以首先想到的是“socks”/使用{“socks”}会产生错误:表达式的非法开始类型“;”的非法开始expected@j.bow尝试<代码>新字符串[] {“袜子”} /代码> .j.鞠躬,如果它有帮助,考虑选择答案,或者通过左边的按钮来投票。