我有一个程序应该计算指定文件中特定字符的所有实例,例如“A”。我得到它来计算字符,有点,除了它只查看单词开头的字符。所以“aa aaa a ba”只会算作4个“A”而不是7个。我已经尽我所能评论了,所以我的思路很清楚,但我对编程还很陌生,所以我提前道歉如果我不清楚。
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);
}
}