程序将点(。)计为字母字符

时间:2018-05-29 16:49:46

标签: java

所以我的任务是创建一个程序,该程序将文件作为输入并计算其中每个字母字符的出现次数。然后我将打印这封信,它发生的次数和频率。 而且我几乎按计划开始工作了。我唯一的问题是,当我打印时,它还会打印文件中的点数(。)。我无法阻止它这样做。请帮助..

public class CountOccurences {
private static Scanner input;

public static void main(String [] args) throws FileNotFoundException {

    DecimalFormat dec = new DecimalFormat("#.000");
    input = new Scanner(new File("story.txt"));

    int[] ltrCtr = new int[127]; // This array counts the number of occurences for every letter / symbol on the ascii table. 

    String str = "";
    // Puts the textfile as a String
    while(input.hasNext()) {
        str += input.next();
    }

    char[] text = str.toCharArray();

    char temp; int tempInt;
    int ctr = 0;

    for(int i = 0; i < text.length; i++) { // Loops through the text 

        temp = text[i]; // Gets the char at i
        tempInt = (int)temp; // Get the ascii value of the char at i  

        ltrCtr[tempInt]++;  

        if(Character.isAlphabetic(text[i])) {
            ctr++;
        }
    }
    System.out.println("Letter" + "     Amount" + "     Freq");
    for(int i = 0; i < ltrCtr.length; i++) {
        if(ltrCtr[i] >= 1 && (int)ltrCtr[i] != 46) {
            System.out.println("   " + (char)i  + "          " +  
                    ltrCtr[i] + "        " + 
                    dec.format((double)ltrCtr[i]/ctr) + "%");

        }
    }

    input.close();

}

}

2 个答案:

答案 0 :(得分:0)

我认为您打算使用isLetter,而不是isAlphabetic

答案 1 :(得分:0)

Mureinik是对的,isLetter解决了你的问题。这是一篇解释isLetter和isAlphabetic之间差异的帖子,以便更清楚:What is the difference between Character.isAlphabetic and Character.isLetter in Java?