Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Nancy Melucci
seal-mask
.a{fill-rule:evenodd;}techdegree
Nancy Melucci
Front End Web Development Techdegree Student 34,543 Points

Initializing an array from information in a text file

I have an assignment to read from a textfile (which I can do) and compare two arrays (which I also can do) but what I cannot figure out how to do is to initialize the arrays from the text, which looks like this:

"Glover 4 Blow Grumpy Crabby Hiddleston Gamble 8 Lowe Donaldson Alexander Sears Hudson Campos Cabrera Walton"

I see the array name, the size and the elements. I have tried making arraylists and just ignoring the first and second strings (Glover 4 and Gamble 8) and just adding the names that follow.

These are supposed to be a person's name, the number of friends and the names of the friends. I think I am supposed to have the scanner read in the name of the array, the size and populate each one. And then do the comparison.

I can post the code for my arraylist version if needed.

Hope that made sense. Thanks.

Nancy M.

2 Answers

Simon Coates
Simon Coates
28,693 Points

I tried demoing going from a string to your array and got the following

class Main {
  public static void main(String[] args) {
    String x = "hello world these are words";
    String[] line = x.split(" ");
    String[] result = new String[line.length-2];
    for(int i = 2; i<line.length; i++)    {
        result[i-2] = line[i];
    }
  }
}

Apart from this Array may be able to return an arraylist using what you get back from split. Anyhow, this is just an idea. I don't use java much. You can do something similar with arraylist.

Nancy Melucci
seal-mask
.a{fill-rule:evenodd;}techdegree
Nancy Melucci
Front End Web Development Techdegree Student 34,543 Points

Thanks for taking the time to help me. I am still not sure how to make the first token in the file be the name of the array and the second be the size. I will keep working on it. I am having a lot of trouble with tokenizing and file processing.

Simon Coates
Simon Coates
28,693 Points

I'm not even sure if dynamic variable names are possible. Is using a map an option? A map on name, where the item looked up is an array using the passed in size.