I am trying to get the contents of a vector.
I have a class which stores user details such as name and password:
package Login;
/**
*
* @author Kutoma
*/
public class User{
private String name;
private String password;
public User(String aName, String password){
name = aName;
this.password = password;
}
public boolean checkPassword(String pass)
{
if(password.equals(pass))
return true;
else
return false;
}
public String getName(){
return name;
}
public String getPassword(){
return password;
}
}
I then have a class called setOfUsers which adds users and finds their names:
package Login;
public class SetOfUsers extends Vector {
private static SetOfUsers register = null;
public SetOfUsers(){
super();
User temp = new User("Adam","12345");
add(temp);
}
public static SetOfUsers getInstance(){
if (register == null)
{ register = new SetOfUsers(); }
return register;
}
public void addUser(User aUser){
super.add(aUser);
}
public User findUserByName(String name)
{
for(int i = 0; i < capacity(); i++){
User user = elementAt(i);
if(user.getName().equals(name)){
return user;
}
}
return null;
}
At the moment I am getting this error java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
However, I have used capacity to find the size of the vector, not sure where I am going wrong here.
My Main program has the following code when login button is clicked it should print out the
user details
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
SetOfUsers register = SetOfUsers.getInstance();
String name = nameText.getText();
User user = register.findUserByName(name);
String passTxt = passText.getText();
user = register.findUserByName(passTxt);
System.out.print(user);
}
解决方案
You're using capacity() which is not the same as size(). See this SO answer for a nice introduction to the differences between the two: https://stackoverflow.com/a/2787405/1370556.
In short, you'll want to loop through size() instead:
for(int i = 0; i < size(); i++){
As an aside, you may want to switch to ArrayLists. Make sure to read up on the differences between Vector and ArrayList in Java: Why is Java Vector class considered obsolete or deprecated?.