2016-07-23 4 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

あなたは地図を使用することができ、このforループの前に上記のコードを置くことをお勧めしたい、個人的に、あなたのプログラムの終わりに向かってこのコードのスニペットを追加する

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

     } 

    } 

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」方法を破ります部分文字列)しかし、これはあなたにいくらか助けてくれることを願っています:)

+0

ありがとうございます。私はこの行にこの – David

+0

を試してみますValueComparator bvc = new ValueComparator(count)。エラーです。その静的コンテキストから参照することはできませんnoniceice変数を言う – David

+0

さて、私はちょうど2つの小さな間違いをコードで修正したが、私は本当に何か静的ではないことを伝えるだろうか分からない...あなたがそれを宣言main()メソッドの中では常に静的でなければなりません。私はちょうどコピー - コードを再度貼り付け、それは私のために正常に動作します –

関連する問題