Arrays and File Input
Hello, all. I've been working on a solution to a problem that I hope you may help me solve. I need to get data from a simple text file and most likely store the data in parallel arrays. Unfortunately, I don't have experience with the two concepts I'm supposed to use: accessing files and tokenizing strings.
The data file will have data like Name/18/M/8 on each line.
I will need to display all the information, and perform boolean expressions on the numbers.
I was thinking of creating parallel arrays, storing all the names in one array, the second token (age) in another, etc....
Using the concept of tokens, I think I can first create arrays of strings, then create separate arrays.
Is this a good solution?
The easiest way to read data from the file is to use the Scanner class. Once you read a line of data you can use String.split to break the line down into the individual data items.
DO NOT use parallel arrays. They are the spawn of Satan. Write a class to encapsulate the data.
Thanks, Junky. I've been reading your posts. They make me crack up. I like how most of you try to be patient with people begging for code, because they don't want to think. :)
Originally Posted by Junky
Anyway, I was thinking of the split (another concept I'm learning on my own) but how can I keep all the data of each line from the text file connected? If they are kept as Strings, that's fine, but the hint given was that I
might have to use parseInt to treat the two numbers as integers. For example, for every record where someone is under 18, I'd need to display their names.
As I said you use a class to encapsulate the data (keep it together). Yes you need to Use Integer.parseInt to convert a String to an int. You can either do this before creating an object or pass or the info as Strings to the object and then convert to an int in the constructor.
Then what you need to do is keep all the objects together. Most experience coders would use an ArrayList but if this is to advanced then just use an array. Once all you data has been read, object created and inserted into an array you would iterate over the array and (with the use of methods of your class) find the objects with an age under 18 and print the name.
This may seem like a lot to understand and cope with but break it down into smaller steps. First thing try reading all the data from the file and print it to the screen. Don't modify it in anyway. Once this is working move onto the next step. etc.
Junky is a cool guy and he doesn't afraid of anything.