2013-09-23 38 views
-1

我需要從文本文件中讀取每行,並按照長度先對其進行排序,然後在原始文檔中對其進行排序,然後再添加行到鏈接列表。從文本文件中讀取行並將它們排序到鏈接列表中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 

回答

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

  4. 線上有多少個非空格字符:使用「s +」分割線。使用for循環添加所有子陣列的長度。

  5. 從arraylist打印時,打印計數+ nonSpaceChars在行+行。

希望這將是足夠的

1

而不是解決它給你的,我會爲你提供各種鏈接,這將幫助你解決你的任務。它可以對字符串進行

1)Readinga file in JAVA

2)各種字符串操作閱讀:String operations

3)排序集合在Java中使用compartors:Collection sorting

+0

謝謝你,這是建議的我一直在尋找的那種! – user2328383

2

你需要使用一個文件和一個掃描儀。該守則將是這個樣子:

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
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); 
     }  
    } 
} 
+0

請勿將DataInputStream用於文本。 –

相關問題