Hi! My problem is that i have an object that needs to be in an array however the array must not be the same size each time I create an array.

I know that you would use the classType[] objectName={new classType(),new classType(),new classType(),etc}; That would only work if I had a knowledge of how many spots in the array I needed.

However, the amount of lines in a file can vary but that number won't vary after you've told the program what file it is so I must figure out a way to get an unknown constant into the program (the program finds the constant and then the constant stays put).


well ...
you just read the nr of lines into an int, without reading the objects to store, and use that int as the size of the array.

this would make what you want possible, if you use the other way to create an array. for instance:

int nrOfElements = readNrOfLines(); 
// this is if each line represents a new object.
ObjectToStore[] inFile = new ObjectToStore[nrOfElements];

now you have an array with the exact amount of elements you need.

After this, you use a for-loop to iterate over the amount of spaces in the array, which is also the same amount as the amount of lines (elements) in the file
and each iteration, you create a new object that you store in the next location in your array.

In that case, would I be reading the number of newlines detected or is there a way of getting that from the file object.

Thank you. because I have been learning java for just a week or two now, I haven't seen all of the ways to declare thing so I didn't even know you could do that.
Thank you,

You can use the java.io.LineNumberReader, which can take a FileReader object in the constructor. The readLine() method on LineNumberReader will return one line from the file as a String. Why not use an ArrayList<String> to store the lines read? That way you don't have to know ahead of time how many lines there are going to be. If you must know the number of lines in the array, just use the size() method on the ArrayList.

Yes. Don't worry about "how big to make the array". Simply read the file and store the lines in an ArrayList (you do not have a preset size on those). If your "assignment instructions" (or whatever) require you to return an array, then, after reading the file, simply use the toArray method on the ArrayList.