2016-07-23 24 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方法以升序對數組進行排序,然後遍歷整個數組以反轉數組中的元素。所以,你應該考慮把這個代碼片段對你的程序的結束,

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

個人而言,我建議把上面的代碼for循環之前,

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

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

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

你可以使用地圖然後使用自寫比較器(我從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)。 theres錯誤。它說非statice變量這不能從靜態上下文引用 – David

+0

好吧,我只是修復了代碼中的2個小錯誤,但我真的不知道它爲什麼會告訴你某些東西不是靜態的......如果你聲明它在main()方法內部,它應該始終是靜態的。我只是複製粘貼代碼,它對我來說工作正常 –