简体   繁体   中英

Only returning the last element in ArrayList

I've been teaching myself java and I've stuck on a problem that no matter what I do can't seem to solve. I've done some research but all the options provided don't seem to work. Hopefully you guys might be able to teach me something.

I have a .txt file that contains:

AccountName1:Password1  
AccountName2:Password2  
AccountName3:Password3  
AccountName4:Password4  
AccountName5:Password5   

The elements of the file are then read and inserted into a List:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public abstract class AccountFileReader {

  private static Scanner sc;

  public static void main(String[] args) {  

      try {         
        // Enables ability to find file in any OS.
           String file = File.separator + "some folder name"
                         + File.seperator + "AccNamePw.txt";

           File f = new File(file);
           sc = new Scanner(f);

           List<AccountInfo> accounts = new ArrayList<AccountInfo>();
           String name = "";
           String password = "";

           while (sc.hasNext()){
            // Reads and checks if there is a new line
               String line = sc.nextLine();
            // Creates delimiter to make the different elements on file f
               String[] details = line.split(":");
            // Initializes 1st element
               name = details[0];
            // Initializes 2nd element
               password = details[1];           
            // Creates new object "a" that has the 2 elements from each line
               AccountInfo a = new AccountInfo(name, password);
            // Adds the "a" object to the "accounts" List
               accounts.add(a);
           }
        // Iterates list and prints out the list
           for(AccountInfo a: accounts){
        // The hiccup is in here somewhere. This for loop isn't working in 
        // a way I think it's supposed to.

        // Create new object of the getter, setter class to use in this loop
           AccountInfo namPw = new AccountInfo(name, password);
              name = namPw.getName();
              password = namPw.getPassword();               
              System.out.println(a.toString() + "         " + name 
                                 + " " + password);
           }
        } catch (FileNotFoundException e) {e.printStackTrace();}
    }
}

The getter/setter class is as follows:

public class AccountInfo{
private String name;
private String password;

public AccountInfo(String name, String password) {
    this.setName(name);
    this.setPassword(password);
}

public void setName(String name) { this.name = name; }

public String getName() { return name; }

public void setPassword(String password) { this.password = password; }    

public String getPassword() { return password; }

public String toString(){ return name + " "+ password; }
}

My output is:

AccountName1:Password1      AccountName5:Password5  
AccountName2:Password2      AccountName5:Password5  
AccountName3:Password3      AccountName5:Password5  
AccountName4:Password4      AccountName5:Password5  
AccountName5:Password5      AccountName5:Password5  

But I want it to return:

AccountName1:Password1      AccountName1:Password1  
AccountName2:Password2      AccountName2:Password2  
AccountName3:Password3      AccountName3:Password3  
AccountName4:Password4      AccountName4:Password4  
AccountName5:Password5      AccountName5:Password5  

I know that the a.toString() is returning correctly but my namPw.getName() and namPw.getPassword() are only giving me the last element of the List.

What am I not understanding and or missing? How do I get namPw.getName() and namPw.getPassword() to return the List correctly?

The problem is the declaration of name and password right before the while loop. These variables store the last encountered username and password. When the while loop ends, these variables store the values AccountName5 and Password5 respectively.

When you enter the second for-loop, you first create a new UserAccount with using name and password which store AccountName5 and Password5 .

If you just want to print this list, you do not need to create a copy of the contents of the list. Just do:

 for(AccountInfo a : accounts) {
     System.out.println(a.toString() + " " + a.getName() + " " + a.getPassword());
 }

It's because of this:

for(AccountInfo a: accounts){
    **AccountInfo namPw = new AccountInfo(name, password);**
          name = namPw.getName();
          password = namPw.getPassword();               
          System.out.println(a.toString() + "         " + name 
                             + " " + password);

You are looping through the AccountInfo objects you already created and then creating a new AccountInfo object and passing in name and password (which get set each time you read in a new line, so the value for them would be the last thing they would be set to when reading the file)

Not sure why you are creating a new AccountInfo object. But in order to get what you want, you'd need to do this:

AccountInfo namPw = new AccountInfo(a.getName(), a.getPassword());

No need to create new object in loop. You are already getting object in a. Remove object creation line. It is creating object with name and and password which is never going to change as it is outside the loop. Checkout the following solution:

for(AccountInfo a: accounts){
        name = a.getName();
        password = a.getPassword();               
        System.out.println(a.toString() + "         " + name + " " + password);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM