I'm new to java and still having issues with arrays. Any help is appreciated here. My program reads data from a CSV input file in the main class and is suppose to use a second class to store each line (array) into an ArrayList in which at some point the main class will print the Array list to the screen. I'm really lost on how to actually implement this.
Sample input
PERSON,ADD,BB222222,Anna
Main class
try{
File inputFile = new File(INPUT_FILENAME);
Scanner scanFile = new Scanner(inputFile);
String aLine;
String[]theLines;
while(scanFile.hasNextLine()){
aLine = scanFile.nextLine();
theLines = aLine.split(",");
if ("PERSON".equals(theLines[0]) && "ADD".equals(theLines[1])){
processPersonAddition(theLines);
}
Method to add each line to the ArrayList
public static void processPersonAddition(String[]theLines){
Person personAdd = new Person();
setPersonAttributes(personAdd, theLines);
personLogImpl.add(theLines);
}
PersonLogImpl class
import java.util.ArrayList;
public class PersonLogImpl {
private boolean add;
private String licenseNumber, firstName
private ArrayList<Person> myList;
public ArrayList<Person> getPersonLog(){
return myList;
}
public boolean add(Object obj){ //add person object to ordered list
ArrayList<String> list = new ArrayList<>();
return add;
}
This is a third class but that is working fine, just used as getter and setter
EDIT: this is the setPersonsAttributes method
private static void setPersonAttributes(Person person, String[]inputLineValues){
person.setLicenseNumber(inputLineValues[2]);
person.setFirstName(inputLineValues[3]);
}
You are almost there!
I would suggest following changes:
Change your 'processPersonAddition' method to following:\\
public static void processPersonAddition(String[]theLines){
Person personAdd = new Person();
setPersonAttributes(personAdd, theLines);
personLogImpl.add(personAdd);
}
Change the declaration of your 'myList' to initialize it.
private List<Person> myList = new ArrayList<Person>();
Then, change the add method in the PersonImpl class to following:
public void add(Person obj){ //add person object to ordered list
myList.add(obj);
}
Later, whenever you want to print all the persons, just iterate through the 'myList' array.
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.