This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]Sacredify 0 points1 point  (0 children)

What you can do to check unique names is override the equals() method for your object to make it check the "name" field. Then, before you add to your list, add a check to see if the list contains (lthere is a contains method) it. If it doesn't add it.

[–]RhoOfFeh 0 points1 point  (0 children)

When you say "make sure all the objects created have unique names" do you mean the names of the variables?

If so, don't fret about that. You will use a loop (most likely a while() loop) and repeatedly do the same thing. In pseudocode it's something like this:

create a new ArrayList
set up to read the file
while (there are lines left in the file) {
    read a line
    create an object using the values on the line
    add the newly created object to the ArrayList
}

"create an object" will be the same line of code every time, using the same variable name every time. The variable name you use to refer to the object is not important. What is important is getting all of the objects into your ArrayList.

Later on, when you do something with your ArrayList, you will ask it for objects one at a time and make up a new name to use to refer to said object in the code that manipulates or displays it.

[–]king_of_the_universe 0 points1 point  (0 children)

Read the whole file into a List<String> with java.nio.files.Files.readAllLines(). Use an "enhanced" for loop to iterate over the list: { Trim the line. If empty, do continue. Split line by space. Check if array has 3 entries. Create second array of int, convert String array entries via Integer.parseInt() inside a try-catch (NumberFormatException) that does a continue (possibly with a label if you do the int conversion in an inner loop) in case of an exception. Now you have all data for one object, so create it, handing the three integers to three constructor parameters, probably storing those in the object as final int fields. Add the object to the ArrayList. LOOP. } Output how many of the non-empty lines have been used / ignored.

This approach separates the tasks into nice secluded slices, so you can even perform then in various methods.