指定したファイル内の「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);
}
}