0

指定したファイル内の「A」などの特定の文字のすべてのインスタンスをカウントするプログラムがあります。単語の先頭の文字のみを調べることを除いて、文字を数えるようにしました。したがって、「aa aaa a ba」は 7 ではなく 4 つの「A」としてカウントされます。私の思考の流れが明確になるようにできる限りコメントしましたが、私はプログラミングにかなり慣れていないので、前もってお詫び申し上げます。私がはっきりしていない場合。

import java.util.Scanner;
import java.io.*;

public class Charcounter
{
public static void main(String[] args) throws IOException
{
    //accumulator
    int sum = 0;

    Scanner kb = new Scanner(System.in);

    //get filename and character to be counted from user
    System.out.println("Enter the name of a file: ");
    String filename = kb.nextLine();
    System.out.println("Enter the name of the character to be counted: ");
    char countedChar = kb.next().charAt(0);

    //check if file exists
    File file = new File(filename);
    if (!file.exists())
    {
        System.out.println("File specified not found.");
        System.exit(0);
    }

    //open file for reading
    Scanner inputFile = new Scanner(file);

    //read file and count number of specified characters
    while (inputFile.hasNext())
    {
        //read a char from the file
        char count = inputFile.next().charAt(0);

        //count the char if it is the one specified
        if (count == countedChar)
        {
             ++sum;
        }

    }

    //close file
    inputFile.close();

    //display number of the specified char
    System.out.println("The number of the character '" + countedChar + "' is : " + sum);
}
}
4

6 に答える 6

2

これは、最初の文字のみを比較しているためです。

 //read a char from the file
 // THIS : only the first character
 char count = inputFile.next().charAt(0);

 //count the char if it is the one specified
 if (count == countedChar)
 {
   ++sum;
 }

すべての文字をループしてから、一致する場合は合計をインクリメントする必要がありますcountedChar..

 String str = inputFile.next()
 for (int i = 0; i < str.length(); i++) {
   char count = str.charAt(i);   
   // check if it matches the countedChar and then increment.
 }
于 2013-10-18T12:27:33.903 に答える
0

代わりに、char 読み取り専用の Reader を使用できます。

BufferedReader reader = new BufferedReader(new FileReader(file));

int read;

while((read = reader.read())>0) if (read==countedChar) count++;

reader.close();
于 2013-10-18T12:48:50.903 に答える
0

クラスの先頭でゼロとして初期化されるゼロの代わりに変数を使用してみてください。次に、カウントするすべての文字に対して増分します。

   //read a char from the file
    char count = inputFile.next().charAt(m);
    ++m;
    //count the char if it is the one specified
    if (count == countedChar)
    {
         ++sum;
    }

次に、メイン メソッドで次のように定義します。

   int m = 0
于 2013-10-18T12:32:42.687 に答える
0

それは、最初の文字だけを読んでいるためです

    String word = inputFile.next();     //read a word
    int counter = 0; 

    for(counter=0;counter<word.length();counter++) // traverse through the word
    { 
        char count = word.charAt(i);       // ith char

        //count the char if it is the one specified
        if (count == countedChar)
        {
             ++sum;
        }
   }
于 2013-10-18T12:28:43.297 に答える