开发者

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

开发者 https://www.devze.com 2022-12-28 17:42 出处:网络
开发者_StackOverflow社区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.
开发者_StackOverflow社区

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 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.


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).


  • Use Scanner to read lines from the input
  • Use Random to generate random numbers
  • Define an Entry class to encapsulate the data for each entry
  • Use Comparator<Entry> and Collections.sort a List<Entry>
    • Or declare Entry implements Comparable<Entry> and use a SortedSet<Entry>

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

  • What is meant by immutable?
  • Overriding equals and hashCode in Java
    • A proper immutable value type would need to @Override both
  • Java: What is the difference between implementing Comparable and Comparator?
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号