我是一名使用Java的初学者,但我找不到解决方案:
$_SERVER['DOCUMENT_ROOT']
我想在for中添加参数,例如public class Company{
private String name;
private int age;
public Company(String n, int a){
name = n;
age = a;
}
/*get and set*/
public static void main(String[] args) {
ArrayList<Company> comp = new ArrayList<Company>();
comp.add(new Company("Tom", 23));
comp.add(new Company("John", 43));
comp.add(new Company("Charles", 25));
}
}
,email
等。但address
适用于新元素,没有参数。
答案 0 :(得分:1)
您需要阅读有关课程members的内容。
public class Company{
private String name;
private int age;
private String email;
private String address;
public Company(String n, int a, String e, String addr){
name = n;
age = a;
email = e;
address = addr;
}
答案 1 :(得分:1)
使用Company
,email
字段(1)扩展address
类,更新构造函数(2),并传递所需的参数(3)。
public class Company {
...
private final String address; // 1
private final String email;
public Company(String n, int a, String address, String email) { // 2
...
this.address = address;
this.email = email;
}
public static void main(String[] args) {
...
comp.add(new Company("Charles", 25, "street", "charles@gmail.com")); // 3
}
}
如果您已经有一个填充了特定字段信息的数组,则可以使用for
:
final List<String> emails = Arrays.asList("first@gmail.com", "second@gmail.com");
for (final String email : emails) {
comp.add(new Company(..., ..., ..., email));
}
答案 2 :(得分:0)
首先,您需要向类添加变量(即每个类实例存储的位置,以及目前的名称或年龄
您必须修改构造函数(或创建另一个)才能获取这些参数,并且最好让getter和setter单独获取或设置这些参数,因此它看起来像这样
public class Company{
private String name;
private int age;
private String email;
private String address;
public Company(String n, int a){
name = n;
age = a;
}
public Company(String n, int a,String email, String address){
name = n;
age = a;
this.email = email; //class instance object email is set to email from method parameter
this.address = address;
}
/*get and set*/
public void setEmail(String email){
this.email=email; //explicit setter
}
public String getEmail(){
return this.email;
}
public static void main(String[] args) {
ArrayList<Company> comp = new ArrayList<Company>();
comp.add(new Company("Tom", 23)); //will work, because I let your constructor
comp.add(new Company("John", 43));
comp.add(new Company("Charles", 25));
Company compToAdd= new Company("preparedFoo",22);
compToAdd.setEmail("fooomail"); //will work because setter
comp.add(compToAdd);
comp.add(new Company("FooName", 30,"fooMail","FooAddress")); //will work because new constructor
}
}