java - 计算并打印文本文件中每个字母的出现次数

标签 java arrays for-loop

我需要打印每个字母在文本文件中出现的总次数。关于如何循环这个有什么想法吗?我已经掌握了基础知识。不确定我是否正确使用了数组。另外,我该如何打印它?

示例文本文件:

你好,我叫扎卡里。我以给人们拍 X 光片为生。

期望的输出:

字母 - 文件中的频率:

a - 7

b - 0

c - 1

d - 1

e - 4

f - 1

g - 2

小时 - 3

我 - 6

j - 0

k - 1

l - 4

米 - 2

n - 3

o - 4

p - 2

q - 0

r - 2

s - 3

t - 2

u - 0

v - 1

w - 1

x - 1

y - 3

z - 1

/*
 * program that reads in a text file and counts the frequency of each letter
 * displays the frequencies in descending order
 */

import java.util.*; //needed for Scanner
import java.io.*;  //needed for File related classes
public class LetterCounter {
  public static void main(String args[]) throws IOException{
    Scanner keyboard = new Scanner(System.in); //Scanner to read in file name
    System.out.println("Enter the name of the text file to read:");
    String filename = keyboard.next();

    //This String has all the letters of the alphabet
    //You can use it to "look up" a character using alphabet.indexOf(...) to see what letter it is
    //0 would indicate 'a', 1 for 'b', and so on.  -1 would mean the character is not a letter
    String alphabet = "abcdefghijklmnopqrstuvwxyz";

    //TODO: create a way to keep track of the letter counts
    //I recommend an array of 26 int values, one for each letter, so 0 would be for 'a', 1 for 'b', etc.
    int[] myArray = new int[26];

    Scanner fileScan = new Scanner(new File(filename));  //another Scanner to open and read the file
    //loop to read file line-by-line
    while (fileScan.hasNext()) {  //this will continue to the end of the file
      String line = fileScan.nextLine();  //get the next line of text and store it in a temporary String
      line = line.toLowerCase( ); // convert to lowercase

      //TODO: count the letters in the current line
      for (int i=0; i<line.length(); i++) {
        myArray[line.charAt(i) - 'a']++; 
      }
    }
    fileScan.close(); //done with file reading...close the Scanner so the file is "closed"



    //print out frequencies
    System.out.println("Letters - Frequencies in file:");

    //TODO: print out all the letter counts


  }
}

最佳答案

实际上,这与存储时正好相反

for (int i = 0; i < myArray.length; i++) {
        System.out.printf("%c has %d%n", i + 'a', myArray[i]);
}

您还需要检查输入字符是否为 alpha

if (Character.isAlphabetic(line.charAt(i))) {
      myArray[line.charAt(i) - 'a']++;
}

这段代码应该被替换

for (int i=0; i<line.length(); i++) {
    myArray[line.charAt(i) - 'a']++; 
}

关于java - 计算并打印文本文件中每个字母的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58810181/

相关文章:

java - Maven 项目安装到 jar,尝试访问路径时出现 404

java - 如何在sencha中调用javascript中的java方法?

java和内存布局

java - 创建集合的适当字符串表示

ios - 在 For 循环结束时显示 UIAlertView...如果没有错误

向量上带有 FOR 循环的 R 函数

c - for(i=0;0;i ) in c 只执行一次为什么?

java - Java 中的按引用传递行为递归 : Combinations and permutations of strings

arrays - 函数并返回 const char*

c - 递归反转一个长度为2^n的整数数组,不修改原数组返回一个新数组