2016-07-23 2 views
0

내가 파일에서 행과 문자의 수를 세는 코드를 작성하기 위해 노력하고있어, 그럼 내가 가지고 올 것 (공간과 쉼표를 포함하여) 모든 문자정렬 문자

을 정렬합니다.

import java.io.BufferedReader; 


     File file1 = new File("C:/input.txt"); 
     BufferedReader in = new BufferedReader(new FileReader(file1)); 

     int nextChar; 
     char ch; 

     int[] count = new int[1000]; 





     in.close(); 
    } 
} 

미리 감사드립니다.

+0

문제를 더 잘 이해할 수 있도록 프로그램의 현재 출력을 포함하도록 질문을 편집하십시오. 그렇게 할 수 없다면 컴파일러 오류가 어디서 발생하는지 설명하십시오. –

답변

1

그래, 까다로운 점은 프리미티브 유형 int의 배열을 내림차순으로 정렬하는 방법입니다. 글쎄, Arrays.sort(array, Collections.reverseOrder());에 대해 이야기하는이 사이트에는 많은 게시물이 있지만이 배열은 객체 배열에만 사용할 수 있으며 int과 같은 기본 유형은 사용할 수 없습니다. 따라서이 방법을 사용하는 가장 좋은 방법은 내장 된 Arrays 메서드를 사용하여 오름차순으로 배열을 정렬 한 다음 전체 배열을 탐색하여 배열의 요소를 뒤집는 것입니다. 그래서 나는

for (i = 0; i < 26; i++) { 

    System.out.printf("%c : %d", i + 'A', count[i]); 

    System.out.println(""); 
} 
1

당신은지도를 사용할 수, 루프이 전에 위의 코드를 넣는 게 좋을 것, 개인적으로, 프로그램의 끝 부분이 코드 조각을 추가

Arrays.sort(count);//sort in ascending order 
for(int i = 0; i < count.length; i++){ //reversing the order of the array 
    int k = count[i]; //swapping the i-th element with the i-th to last element 
    count[i] = count[count.length - 1 - i]; 
    count[count.length - 1 - i] = k; 
} 

을 고려해야한다 그런 다음 자체 작성 비교기 (나는 this 스레드의 코드를 훔쳤다)를 사용하여 정렬합니다. 이렇게하면 배열에서 사용할 문자를 미리 정의 할 필요가 없습니다.

이 이런 모양 일 :

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Comparator; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.TreeMap; 

public class CountCharsFromFile { 
    static BufferedReader b; 

    public static void main(String[] args) { 

     try { 
      FileReader fr = new FileReader("C:\\test.txt"); 
      b = new BufferedReader(fr); 

      Map<String, Double> count = new HashMap<String,Double>(); 
      ValueComparator bvc = new ValueComparator(count); 
      TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc); 

      int totalChars = 0; 
      int totalWords = 0; 

      String currentLine; 

      while ((currentLine = b.readLine()) != null){ 
       for (int i = 0; i < currentLine.length(); i++) { 

        //Char count: 
        totalChars += 1; 

        //Adding all chars to the Map: 
        char currentChar = Character.toLowerCase(currentLine.charAt(i)); 

        if (! count.containsKey(String.valueOf(currentChar))){ 
         count.put(String.valueOf(currentChar), 1.0); 
        }else{ 
         count.put(String.valueOf(currentChar), count.get(String.valueOf(currentChar)) + 1); 
        } 

       } 

       //Counting words: 

       String[] currentLineSplit= currentLine.split("\\s+"); 

       for (String string : currentLineSplit) { 
        totalWords += 1; 
       } 

      } 

      sorted_map.putAll(count); 

      //Output: 
      System.out.println("Words: " + totalWords); 
      System.out.println("Chars: " + totalChars); 
      System.out.println(sorted_map.toString()); 


     } catch (FileNotFoundException e) { 
      System.err.println("Error, file not found!"); 
      e.printStackTrace(); 
     } catch (IOException e) { 
      System.err.println("Error reading file!"); 
      e.printStackTrace(); 
     }finally{ 
      try { 
       b.close(); 
      } catch (IOException e) { 
       System.err.println("Couldn't close the BufferedReader!"); 
       e.printStackTrace(); 
      } 

     } 

    } 
} 




//comparator class: 

class ValueComparator implements Comparator<String> { 
    Map<String, Double> base; 

    public ValueComparator(Map<String, Double> base) { 
     this.base = base; 
    } 

    // Note: this comparator imposes orderings that are inconsistent with 
    // equals. 
    public int compare(String a, String b) { 
     if (base.get(a) >= base.get(b)) { 
      return -1; 
     } else { 
      return 1; 
     } // returning 0 would merge keys 
    } 
} 

출력은 다음과 같습니다

Words: 9 
Chars: 59 
{ =16.0, h=7.0, i=5.0, r=4.0, c=4.0, �=3.0, s=3.0, o=3.0, l=3.0, f=3.0, ,=2.0, w=1.0, u=1.0, n=1.0, m=1.0, b=1.0, a=1.0} 

"sorted_map.toString()"의 출력은 정말 좋은하지 않습니다, 그래서 빠른 썼다 출력 방법 : 당신과 같이 전화

static void output(TreeMap<String, Double> sm) { 

     String map = sm.toString(); 

     if (map.length() > 2) { //If the map is empty it looks like this: {} 

      map = map.substring(1, map.length() - 1); //cutting the leading and closing { } 

      String[] charCount = map.split(", "); //Splitting 

      //And then formatting: 
      for (String string : charCount) { 
       if (string.charAt(0) == ' ') { 

        string = string.substring(1, string.length() - 2); 
        string = " " + string.substring(0, 1) + " " + string.substring(1, string.length()); 
        System.out.println("SPACE" + string); 

       } else { 

        string = string.substring(0, string.length() - 2); 
        string = string.substring(0, 1) + " " + string.substring(1, 2) + " " 
          + string.substring(2, string.length()); 
        System.out.println(string); 
       } 
      } 

     } 

    } 

:

,536,913 63,210
System.out.println("Words: " + totalWords); 
    System.out.println("Chars: " + totalChars); 
    System.out.println(); 
    //System.out.println(sorted_map.toString()); <--- old 
    output(sorted_map); 

그리고 출력은 다음과 같습니다 가고있다

Words: 9 
Chars: 60 

SPACE = 8 
R = 6 
T = 5 
E = 5 
A = 5 
N = 3 
U = 2 
O = 2 
M = 2 
L = 2 
I = 2 
H = 2 
. = 1 
Z = 1 
Y = 1 
X = 1 
W = 1 
V = 1 
S = 1 
Q = 1 
P = 1 
K = 1 
J = 1 
G = 1 
F = 1 
D = 1 
C = 1 
B = 1 

와, 그것을 가지고 조금 지저분한 (비교기 내가 사용하여 해결 방법을 구축했다 그래서 "TreeMap.get"방법을 나누기 substrings) 그러나 이것이 다소 도움이되기를 바랍니다 :)

+0

정말 고마워요. 나는이 라인에서 – David

+0

을 시도 할 것입니다. ValueComparator bvc = new ValueComparator (count). 오류입니다. 그것은 정적 인 컨텍스트에서 참조 할 수없는 non statice 변수를 말합니다. – David

+0

그래, 코드에서 2 개의 작은 실수를 수정했지만, 왜 정적이 아닌지 당신에게 말할 수있는 이유를 모르겠습니다 ... 선언하면 main() 메서드 내에서는 항상 정적이어야합니다. 난 그냥 복사 - 코드를 다시 붙여 그것은 나를 위해 잘 작동 –