简体   繁体   中英

I need to take an array of three lines in a text file and sort them base on the first line in Java

I need to take an array of three lines in a text file and sort them base on the first line in Java. I also need to manipulate this as well and then print to screen.

I have a test file that is formatted like this:

10
Michael
Jackson
12
Richard
Woolsey

I need to input this from a text file and then rearrange it based on the number associated with the name. At that point, I need to use a random number generator and assign a variable based on the random number to each name. Then I need to print to screen the variable I added and the name in a different format. Here is an example of the output:

12:
Woolsey, Richard
Variable assigned
10:
Jackson, Michael
Other variable assigned

I highly appreciate any help. I ask because I do not really know how to input the three lines as one variable and then manipulate later on in the program. Thanks, Cory

I'm not really sure I understand your question. Except for the sorting, maybe something like this below would help. Please note that this is an incomplete solution where no input is stored, and the output is simply being printed out once (and then discarded).

Random generator = new Random();

try { BufferedReader in = new BufferedReader(new FileReader("filename")); 
      String str; 

      String firstName = null:

      while ((str = in.readLine()) != null) { 

             // try to create an Integer out of the "str"-variable
            Integer nr = null;
            try{
              nr = Integer.parseInt(str);
              firstName = null;
            }
            catch (NumberFormatException e) { 
                  //line was not a number

                  if (firstName != null) {
                     // str is the last name
                     System.out.println(nr);
                     System.out.println(str + ", " firstName + " " + generator.nextInt());
                  }
                  else {
                    firstName = str;
                  }
            }
      } 
      in.close(); 
} 
catch (IOException e) { } 

Please note that this does not do any sorting whatsoever. Take a look at a Comparator for that part. You could also use java.util.Scanner to read the input from the command line (if it is not lying around in a file).

This snippet should be instructive:

import java.util.*;
import java.io.*;

public class Entry implements Comparable<Entry> {
    final int id;
    final int whatever;
    final String firstName;
    final String lastName;

    Entry(int id , String firstName, String lastName, int whatever) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.whatever = whatever;
    }
    @Override public String toString() {
        return String.format(
                "%d:%n%s, %s%n(%d)%n",
                id, lastName, firstName, whatever);
    }
    @Override public int compareTo(Entry other) {
        return
            (this.id < other.id) ? +1 :
            (this.id > other.id) ? -1 :
            0;
    }
}

Here we have encapsulated each Entry in its own immutable value type class. It also implements Comparable<Entry> , comparing the id (assumed to be unique) in descending order.

We can now use a SortedSet<Entry> to do the rest:

    public static void main(String[] args) throws FileNotFoundException {
        SortedSet<Entry> entries = new TreeSet<Entry>();
        Scanner sc = new Scanner(new File("sample.txt"));
        Random r = new Random();
        while (sc.hasNextInt()) {
            int id = sc.nextInt();
            sc.nextLine();
            String firstName = sc.nextLine();
            String lastName = sc.nextLine();
            int whatever = r.nextInt();
            entries.add(new Entry(id, firstName, lastName, whatever));
        }
        for (Entry e : entries) {
            System.out.println(e);
        }
    }

If the sample.txt contains the following:

10
Michael
Jackson
12
Richard
Woolsey

Then an output may be:

12:
Woolsey, Richard
(-1279824163)

10:
Jackson, Michael
(320574093)

See also

I saw your post and I thought to give you a fast answer.

Check out this link: Reading file line by line

You should go through the Java Tutorials as well.

After you take each line you can save into a two dimensional array with something like this:

  String str; 
  i = 0;
  j = 0;
  while ((str = in.readLine()) != null) { 
         array[i][j] = str;
         j++;
         if (j == 3){
            j = 0;
            i++;
         }
  } 
  in.close();

Then you can play with the array values any way you like.

Good luck.

I asked a similar question awhile back .

The combo of Scanner + Matcher with an appropriate regex is pleasantly effective at extracting formatted data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM