Help reading a txt file into a datatype similar to a db
For my project I in phase 1 we cannot use a database and I am having trouble figuring out what to do. the textfiles are like
ProductID1 ProductName1 Price1 Quantity1
ProductID2 ProductName2 Price2 Quantity2
ProductID3 ProductName3 Price3 Quantity3
ProductID4 ProductName4 Price4 Quantity4
ProductID5 ProductName5 Price5 Quantity5
^with actual data though
I know how to read in the files using StringTokenizer, I just don't understand what datatype to place everything in because everything I've been working with so far that I've known java is 1D Arrays/Lists. When you have 4, 5, or 6 colums what to can I do when I don't have a DB to hold the information and I need to access it easily. I looked on google and it seemed like I should use a Map or HashMap but I still don't see any examples of how to use one when you have 4 columns of data for each row. If anyone can shield some light on what to do I'd be grateful.
Re: Help reading a txt file into a datatype similar to a db
You could define a class to hold the data and save instances of the new class in an ArrayList.
Or you could define a two dimensional array and save the tokens from the file as Strings in the array.
The first dim would be the row, the second dim would be the column on that row.
How will the data be accessed? Sequentially or by a key?
Re: Help reading a txt file into a datatype similar to a db
by key. So going with your first advice, I create a class similar to this but with getters and setters and a constructor like
public class Product {
public Product(int id, String name, float price, int quantity){
//set private values here
}
//getters and setters here
}
then make my readFile from my driver return an Arraylist of instances of my Product class i assume. After that how do I iterate through my objects? I will want to search by the id for example. i need to figure out how to access my objects from an arraylist..ill google it shortly unless i get a reply. thanks.
Re: Help reading a txt file into a datatype similar to a db
If you are accessing the data by key, you will want to use a Map instead of an ArrayList.
Re: Help reading a txt file into a datatype similar to a db
Alright, I'll see what I can do. If I need any more help I'll come back to this thread. I appreciate it. I wasn't able to even think of the idea of an Map/List of objects until you helped me so thanks I should be able to figure it out from here.
--- Update ---
thank you Norm! i got it working with a HashMap and a Product class. Thanks again