簡體   English   中英

從文本文件中讀取行並將它們排序到鏈表Java中

[英]reading lines in from a text file and sorting them into a linked list java

我需要從文本文件中讀取每一行,並先根據長度對其進行排序,然后再將其在原始文檔中的位置,然后再將這些行添加到鏈接列表中。

然后必須逐行打印出列表的內容,並帶有一個前綴,該前綴指示要打印出的行號以及該行上有多少非空格字符。

以下是一個示例I / O:

Input (i.e. contents of text file)

this
is
just
a
test

Output

1/1: a
2/2: is
3/4: this
4/4: just
5/4: test

您需要使用文件和掃描儀。 代碼看起來像這樣:

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

public class ReadAndWrite {
    public static void main(String[] args) throws IOException {

        Scanner scan = new Scanner(new File("yourfile.txt"));

        int i = 1;
        while(scan.hasNext()) {
            String s = scan.nextLine();
            System.out.println("Line " + i + " says " + s + " and has " + s.length() + " characters.";
            i++;
        }
        System.out.println("/nNo more lines in the file.");
    }
}

除了為您解決問題之外,我還將為您提供各種鏈接,這些鏈接將幫助您解決任務。

1) 在JAVA中讀取文件

2)可以對讀取的字符串執行各種字符串操作: 字符串操作

3)使用比較器在JAVA中對集合進行排序集合排序

  1. 我需要從文本文件中讀取每一行:使用FileReader和BufferedReader
  2. 並先根據長度對其進行排序,然后再將其在原始文檔中的位置,然后再將這些行添加到鏈接列表中:使用原始文檔的(String,lineNo)創建一個HashMap。
  3. 使用Comparator首先按長度排序,然后使用三元運算符按pos行(從hashMap中獲取)進行排序。

  4. 該行上有多少個非空格字符:使用“ s +”分隔行。 使用for循環添加所有子數組的長度。

  5. 從arraylist打印時,在line + line中打印count + nonSpaceChars。

希望這將足夠

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

public class HelloWorld{

public static class mystruct {
    public String line;
    public int    number;
    public mystruct(String line, int count) {
        this.line = line;
        this.number = count;
    }
}

  public static void main(String []args){
     LinkedList<mystruct> list = new LinkedList<mystruct>();
     mystruct  temp;
     int count=0;
      try{
          FileInputStream fstream = new FileInputStream("input.txt");
          BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
          String readline;
          while ((readline = br.readLine()) != null) {
              count++;
              temp = new mystruct(readline, count);
            list.add(temp);
          }
          in.close();
         } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
         }      
         Collections.sort(list, new Comparator<mystruct>() {
             public int compare(mystruct o1, mystruct o2) {
                 if (o1.line.length() != o2.line.length())
                    return (o1.line.length() - o2.line.length());
                else {
                    return (o1.number - o2.number);
                }
             }
         });
          for (int i = 0; i < list.size(); i++) {
            temp = list.get(i);
            System.out.println(temp.line);
        }      
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM