2013-09-23 5 views
-1

텍스트 파일에서 각 라인을 읽고 길이를 먼저 정렬 한 다음 원래 문서의 위치에 따라 정렬해야합니다. 링크 된 목록에 선.텍스트 파일에서 라인을 읽고 링크 된 목록으로 정렬하기 자바

목록의 내용은 인쇄 할 행 번호를 나타내는 접두사와 행에 공백이 아닌 문자가 몇 행씩 인쇄되어야합니다.

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. 비교기를 사용하여 길이별로 정렬 한 다음 3 진수 연산자를 사용하여 라인 pos (hashMap에서 가져옴)로 정렬합니다.

  4. 줄에 공백이 아닌 문자가 몇 개인 지 : "s +"를 사용하여 줄을 나눕니다. for 루프를 사용하여 모든 하위 배열의 길이를 추가하십시오.

  5. arraylist에서 인쇄하는 동안 line + line의 print count + nonSpaceChars.

희망이

1

이 대신 당신을 위해 그것을 해결의 난 당신이 과제를 해결하는 데 도움이 될 것입니다 다양한 링크를 제공합니다 : 아래

는 I/O는 샘플입니다. 문자열에서 수행 할 수있는

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을 사용하지 마십시오. –

관련 문제