1

我正在做一个项目,但程序的这一部分不起作用。它要求输入一个字符,然后读取一个给定的文本文件,并输出该字母在文本文件中出现的百分比。这是代码:

public static void inputLetterFrequency() {
    String letterInput = JOptionPane.showInputDialog("Please input a letter to find out the frequency");
    letterInput.toUpperCase();
    char c = letterInput.charAt(0);
    content = content.toUpperCase();

    for (int i = 0; i < content.length(); i++) {
        if (content.charAt(i) == c) {
            letterOccurence++;
        }
    }

    letterFrequency = (letterOccurence / numberCharacters) * 100.0;

    JOptionPane.showMessageDialog(null, "Frequency of letter " + c + " is " + letterFrequency + "%");
    String tryAgain = JOptionPane.showInputDialog("Please choose an option: \n1 to input another letter \n2 to exit ");
    int n = Integer.parseInt(tryAgain);
    if (n == 1) {
        CharacterAnalyzer.inputLetterFrequency();
    } else {
        System.exit(0);
    }

以下是在文件开头声明的

public static int numberCharacters;
public static String Filename = UserPrompt.content;
public static int letterOccurence;
public static double letterFrequency;
public static int digitOccurence;
public static double digitFrequency;
4

1 回答 1

6

这是您计算的代码letterFrequency:-

letterFrequency = (letterOccurence / numberCharacters) * 100.0;

只需将上面的代码更改为: -

letterFrequency = letterOccurence * 100.0 / numberCharacters;

在第一个代码中: -(letterOccurence / numberCharacters)将首先被评估,因为这是一个integer division,它的结果将是0,如果numerator小于denominator

要使其成为floating-point division,只需将分子与100.0之前相乘即可dividing

于 2012-11-27T23:18:08.450 回答