Results 1 to 2 of 2
  1. #1
    earthw0rmjim is offline Member
    Join Date
    Apr 2012
    Posts
    1
    Rep Power
    0

    Default How should i do this?

    Hey!

    I'd like to ask for some help, since i'm kinda new to Java.
    I need to write a program that gets 2 parameters. First one is an input file (simple hand-written txt file), the second is an int. The int defines the number of the word the lines shoud be sorted by. Kinda hard to explain, so here's an example:

    The file contains:

    AAA AAA AAA
    AAA BB A
    BBB AAA AAA
    BB AA BB
    CCC AA C
    AA BBB CC

    If the program gets 1 as the 2nd parameter, the lines must be sorted by the first word of each line.
    Should look like this:

    AAA AAA AAA
    AAA BB A
    AA BBB CC
    BBB AAA AAA
    BB AA BB
    CCC AA C

    If the 2nd parameter is 2, then the lines must be sorted by the second word of each line.
    Like this:

    AAA AAA AAA
    BBB AAA AAA
    BB AA BB
    CCC AA C
    AAA BB A
    AA BBB CC

    And so on...

    I know the basics, how to work with files, use BufferedReader and stuff.
    But i have no idea how should i do this. TreeSet maybe? How can i sort lines by words other than the first in the line?

    I'd appreciate any advice on this matter.
    Thanks in advance!
    Last edited by earthw0rmjim; 04-19-2012 at 11:21 PM.

  2. #2
    jlczuk is offline Senior Member
    Join Date
    Apr 2012
    Location
    New York State of Confusion, USA
    Posts
    137
    Blog Entries
    1
    Rep Power
    0

    Default Re: How should i do this?

    One way would be to simply use String arrays (String[][]) so you can pick each line apart the first dimension represents each line and the second dimension represents each word in that line. It's brute force in terms of data structure, but it's simple and lets you access what you need to in the positions you need. I'd have to look at the Java tutorials to see about sorting, but you can do that just as easily too.

    Alternatively, you could construct a Map where each entry is an input line and the key is the word in that line whose index your second parameter specified.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •