-1

我正在尝试编写一个程序,提示用户输入一个字符,并计算所述字符出现在给定文件中的实例数。并显示字符出现的次数。

我真的很茫然,很抱歉我还没有很多代码,只是不知道从哪里开始。

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

public class CharCount {

    public static void main(String[] args) throws IOException {
        int count = 0;
        char character;

        File file = new File("Characters.txt");
        Scanner inputFile = new Scanner(file);

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter a single character");
        character = keyboard.nextLine().charAt(0);  
  }
}
4

1 回答 1

2

您需要以下代码从文件中读取并使用您输入的字符进行检查。count将包含指定字符的出现。

try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = null;
        while ((line = reader.readLine()) !=null) {
            for(int i=0; i<line.length();i++){
                if(line.charAt(i) == character){
                    count++;
                }
            }
        }
    } catch (FileNotFoundException e) {
        // File not found
    } catch (IOException e) {
        // Couldn't read the file
    }
于 2013-03-06T06:40:10.023 回答