【问题标题】:Counting a specific character in a file with Scanner使用扫描仪计算文件中的特定字符
【发布时间】:2013-03-06 06:30:20
【问题描述】:

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

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

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);  
  }
}

【问题讨论】:

标签: java character java.util.scanner


【解决方案1】:

您需要以下代码从文件中读取并与您输入的字符进行检查。 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
    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多