java - 计算字母出现次数

标签 java if-statement letter file-io find-occurrences

程序需要统计并显示指定字符在文本文件中出现的次数。

目前总数为零。我不知道是否应该使用不同的循环,我也尝试过使用“for”循环。

// Hold user input and sum
String fileName;    // Holds the name of the file
String letter;      // Letter to search for in the file
int total = 0;      // Holds the total number of characters in the file


// Get the name of the file and character from the user
fileName = JOptionPane.showInputDialog("Please enter the name of a file:");
letter = JOptionPane.showInputDialog("Please enter a letter contained in the string");


// Open the file for reading
File file = new File(fileName);         
Scanner inputFile = new Scanner(file);  // Declare new scanner object for file reading


// Set accumulator to zero
int count = 0;

if (inputFile.nextLine().equalsIgnoreCase(letter)) {                                

    count++;          // add letter occurrence

    total += count;   // add the letter occurrence to the total
}

最佳答案

    BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
    int ch;
    char charToSearch='a';
    int counter=0;
    while((ch=reader.read()) != -1) {
        if(charToSearch == (char)ch) {
            counter++;
        }
    };
    reader.close();

    System.out.println(counter);

这有什么帮助吗?

关于java - 计算字母出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15021163/

相关文章:

java - 并行运行操作,同时保留有序的增量输出

java - 查找 2 个参数的最小值

java - 无法将驱动器号放入java中的文件路径中

javascript - 带有 :contains condition 的 switch 语句

Java使文件阅读器考虑特定字母

php - 如何检查一个字符是字母还是数字?

java - Android Studio 中的断点 C++ 文件

java - 可运行的子类,普通的父类(super class),如何运行子类?

java - 使用 Stream 展平嵌套 Hashmap

java - if/else 和 switch 语句的操作有区别吗?