public class Start {
public Register theReg = new Register();
public static Start go = new Start();
public static void main(String[] args) {
Register theReg = new Register();
go.regUsers();
if(theReg.logIn("jsmith","password")) {
System.out.println("You're logged in as " +
theReg.userLoggedIn.getName());
} else {
System.out.println("dang");
}
}
public void regUsers() {
Student regJoe =
theReg.regSeniorStaff("Joe smith", "password", "jsmith", 1);
}
}
public class Register {
public ArrayList<People> users;
public People userLoggedIn;
public Register () {
users = new ArrayList<People>();
users.add(new Student("john","password","jo",1));
userLoggedIn = null;
}
public Student regStudent(String name, String password,
String username, int stuId) {
Student s = new Student(name, password, username, stuId);
users.add(s);
return s;
}
}
我想我刚刚错过了一些愚蠢的事情。就像....
start 方法将创建一个新的 Register
对象,该对象具有其 ArrayList
。然后,它开始使用 regStudent
等方法注册用户。但是,只有 Register
上的构造函数允许我将对象添加到 ArrayList
中;稍后调用这些方法来做同样的事情只是不会添加它们。它创建对象但无法添加它们。也无法删除东西,只有 .get
可以在其中工作。
任何帮助都会很棒,谢谢!
最佳答案
看起来您正在隐藏您的 theReg
全局变量。您很可能查询全局并看到只有构造函数添加的项位于您的 ArrayList 中。
public class Start {
public Register theReg = new Register(); //<<---- your global var
public static Start go = new Start();
public static void main(String[] args) {
Register theReg = new Register(); // <<---- hiding the global
go.regUsers();
if(theReg.logIn("jsmith","password"))
System.out.println("You're logged in as " + theReg.userLoggedIn.getName());
else
System.out.println("dang");
}
}
关于Java ArrayList 不允许我从外部构造函数添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1884486/