计算和打印文本文件中每个字母的出现

时间:2019-11-11 23:54:02

标签: java arrays for-loop

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

示例文本文件:

你好,我叫扎卡里。拍摄人们的X光片是我的谋生手段。

所需的输出:

字母-文件频率:

a-7

b-0

c-1

d-1

e-4

f-1

g-2

h-3

i-6

j-0

k-1

l-4

m-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


  }
}

1 个答案:

答案 0 :(得分:1)

真的只是存储时间的倒数

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

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

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

此代码应替换

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