简体   繁体   English

我需要在文本文件中采用三行数组,并根据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 need to take an array of three lines in a text file and sort them base on the first line in Java. 我需要在文本文件中使用三行​​数组,并根据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). 您也可以使用java.util.Scanner从命令行读取输入(如果它不在文件中)。

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. 在这里,我们将每个Entry封装在其自己的不可变值类型类中。 It also implements Comparable<Entry> , comparing the id (assumed to be unique) in descending order. 它还implements Comparable<Entry> ,以降序比较id (假定为唯一)。

We can now use a SortedSet<Entry> to do the rest: 现在,我们可以使用SortedSet<Entry>进行其余操作:

    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: 如果sample.txt包含以下内容:

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. 您也应该阅读Java教程。

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. Scanner + Matcher与适当的正则表达式的组合在提取格式化数据方面非常有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我需要一个文件读取器来逐行读取文本文件并将其格式化为Java - I need to get a file reader to read a text file line by line and format them in Java 我需要一次接听所有线路并与他们一起工作,但我得到了逐行接收 - I need to take all the lines at once and work with them, but I get line-by-line reception 在Java中,我需要读取一个文本文件并将每一行放在单独的数组中。 但是每次阅读文本文件时,我都无法分开 - In Java I need to read a text file and put each line in a separate array. But every time I read the text file I cannot split the lines 如何从文本文件中取出特定行并将其读入数组? (爪哇) - How to take a specific line from a text file and read it into an array? (Java) Java:如何从文本文件的每一行中提取第一个单词并将其写入新的文本文件? - Java: How to take the first word in each line from a text file and write it to a new text file? 来自文本文件的Java排序行 - Java sort lines from text file Java,将文本分类为行 - Java, sort text into lines Java从文本文件读取前两行 - Java Reading First 2 lines from Text File 需要帮助来从文本文件中读取行并将其添加到ArrayList - Need help reading lines from a text file and adding them to an ArrayList 从文本文件中获取值并将其放入数组中 - Take values from a text file and put them in a array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM