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<User> {
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);
}
Use size() instead of capacity().
capacity():
returns the current capacity (the length of its internal data array, kept in the field elementData of this vector)
size():
returns the number of components in this vector.
Check the docs here .
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? .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.