私は、Javaに新しいですし、私のコードは、テキストファイルと文字の発生の両方をプリントアウトしていない理由を把握することはできません

JavaLearner:

アレイは、文字の正確な量を印刷しかし、私のコード印刷のみファイルの最初の行とラインカウントは1です。どのように私は両方のテキストや手紙発生を印刷するには、私のコードを変更することができます。また、私は、事前にそのようなシンボルやspaces.Thanksとして配列非アルファベット文字の第27位に印刷したいです。

 import java.io.*;
 public class Test { 
 public static void main(String[] args)throws Exception {

     int lineCount=0; // Variale used to count the numbers of line. 
     int nextChar;
     char c;

     File file = new File("file.txt");  //  file in same folder

     BufferedReader readFile = new BufferedReader(new FileReader(file)); 
     String lines= " "; 
     int[] count = new int[27];
     char ch;

     while ((lines = readFile.readLine()) != null){

        System.out.println(lines);
        while ((nextChar = readFile.read()) != -1) {
        ch = ((char) nextChar);

            // Does this code count even uppercase or shall i  
            // convert it the text to lower case.

            if (ch >= 'a' && ch <= 'z'){
                count[ch - 'a']++;

            }
        }
        lineCount++;
    }

    System.out.println("file.txt containes " + lineCount + " lines.");

    for (int i = 0; i < 26; i++) {
        System.out.printf("%c %d", i + 'A', count[i]);
    }        
} 
} 
jste89:

あなたのオリジナルの答えと非常に接近していました!

主な問題は、ネストされたwhile最初の行が印刷され、カウントが正確であったが、他の行が印刷されていなかったた理由です-ファイルの最後に読んでいたループ。されている理由BufferedReader(名前が示唆するように)バッファによってバックアップされています。最初の呼び出しreadLine返されたString最初の改行文字に、バッファ内のすべての文字を含みます。各呼び出しreadは次の方法、それはその時点で、ファイルの終わりに達するまでループは次いで一文字による沿っバッファの位置を移動させながら、readメソッド戻り-1、ループが終了します。時間によって第2の呼をreadLineので、バッファが終了位置に既に作られてnull戻されます。

あなたは、ReadLineメソッドの呼び出しから返されたライン内のバイトを反復処理することによって問題を解決することができます。

ここでは作業例を示します。

public static void main(String[] args) throws Exception {
    int lineCount = 0;// Variale used to count the numbers of line.
    File file = new File("file.txt");  //  file in same folder

    BufferedReader readFile = new BufferedReader(new FileReader(file));
    String lines;
    int[] count = new int[27];
    char ch;

    while ((lines = readFile.readLine()) != null) {
        System.out.println(lines);
        for (byte charByte : lines.getBytes()) {
            ch = (char) charByte;

            // Does this code count even uppercase or shall i convert
            // it the text to lower case.

            if (ch >= 'a' && ch <= 'z') {
                count[ch - 'a']++;
            // Count non-alpha characters here. Node: this will count numeric values also...
            } else if (ch < 'A' || ch > 'Z') {
                count[26]++;
            }
        }
        lineCount++;
    }

    System.out.println("file.txt containes " + lineCount + " lines.");

    for (int i = 0; i < 26; i++) {
        System.out.printf("%c: %d\n", i + 'A', count[i]);
    }
    System.out.printf("Special characters: %d\n", count[26]);
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=218217&siteId=1