Adding an object to Arraylist from text files
Hello guys!
This is my "Call" class (without the setters and getters):
Code Java:
import java.util.ArrayList;
public class Call {
private String callingNumber;
private String dialedNumber;
private String datetime;
private int duration;
static ArrayList <Call> calls = new ArrayList<Call>();
public Call (String callingNumber , String dialedNumber, String datetime, int duration)
{
this.callingNumber = callingNumber;
this.dialedNumber = dialedNumber;
this.datetime = datetime;
this.duration = duration;
calls.add(this);
}
My application needs to read a text file and then create the corresponding "Call". The "document.txt" keeps the data of a call in every line (callingNumber, dialedNumber, datetime, duration)
(e.g. 4748832, 462346214, 01-01-2012 11:55:33, 126
64364366, 62346547, 03-03-2012 11:55:33, 65 ) .
I thought that i should "read" the line (in my main method) and add it to the calls ArrayList. Something like this:
Code Java:
public static void main (String args[]) throws IOException {
try {
File file1 = new File("C:\\...\\document.txt");
Scanner Filereader1 = new Scanner(file1);
while (Filereader1.hasNextLine()) {
String a = Filereader1.next();
Call.calls.add(a)
}
}
catch (FileNotFoundException e) {
System.out.println("error" + e);
}
}
This is not working because "Call.calls.add()" method can only add "Call" objects which the line of the document is not.
Any suggestions?
Thanks.
Re: Adding an object to Arraylist from text files
You are trying to add String but actually the arraylist is of type Call. Reference the Java 7 API and leave the old habit of creating List.
Code :
List<Integer> list = new ArrayList<>();
Re: Adding an object to Arraylist from text files
You are defining your ArrayList to only generically accept Call objects. You are trying to add a string to this collection which is a syntax error. You need to instantiate a new Call object and add that to the array using that nice constructor you made. Try splitting the string you read by the comma ',' deliminator and passing them as parameters to the constructor.
Re: Adding an object to Arraylist from text files
Thankw a lot guys. I used the split() method as ChristopherLowe proposed an it worked.