Java中的字母频率程序

时间:2015-12-07 18:40:56

标签: java

我正在尝试编写一个字母频率程序,用于计算 .txt文件中的字母字符,并在2列表格中显示频率数据。我无法弄清楚如何从显示功能调用函数printChars。我也坚持在printChars函数中输出频率数据。有人有什么建议吗?感谢。

这是我的代码:

        final static int AlphabetSize = 26;
final static Scanner cin = new Scanner(System.in);
final static PrintStream cout = System.out;
final static int MaxBarLength = 50;

public static void main(String[] args) {
    String fileName;




    // get the file name
    cout.print("Enter the file name: ");
    fileName = cin.nextLine();

    // process the file
    try {
        processFile(fileName);
    }
    catch (IOException e) {
        e.printStackTrace();
    } // end try



} // end main

static void processFile(final String fileName) 
        throws FileNotFoundException, IOException 
{
    FileInputStream inFile = new FileInputStream(fileName);
    int inputValue;

    // declare other variables you need
            int counters [] = new int [26];

    // get the first character from file
    inputValue = inFile.read();
    while (inputValue != -1) {
        char ch = (char) inputValue;

        // add code to process this character
                   if (ch >= 'a' && ch <= 'z'){
                       counters[ch - 'a']++;
                   }

        // read next input character
        inputValue = inFile.read();
    } // end loop

    inFile.close();

    // generate appropriate output
            display(counters);

} // end function

static void display(final int [] counters) {
    // write code for this function

    System.out.println("Letter" + " " + "Count");
    System.out.println("------" + " " + "-----");
   printChars(n, c);
   } // end function

// char2int is complete
static int char2int(final char arg) {
    if (!Character.isLetter(arg))
        return -1;
    else
        return (int) Character.toUpperCase(arg) - (int) 'A';
} // end function


// function printChars writes n copies of the character c to the
// standard output device
static void printChars (final int n, final char c) {
    // write the code
    for (int i = 0; i < 26; i++){
       System.out.printf("%c%7d\n", i + 'A', counters[i]);
   }

           }

 // end printChars

1 个答案:

答案 0 :(得分:0)

您需要更改printChars的签名以获取计数器数组:

static void printChars (final int[] counters) {
    for (int i = 0; i < 26; i++){
       System.out.printf("%c%7d\n", i + 'A', counters[i]);
   }
}

现在你可以通常的方式调用它:

printChars(counters);

Demo.