Java程序打印出0而不是百分比

时间:2012-11-27 23:17:11

标签: java file input joptionpane

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

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;

1 个答案:

答案 0 :(得分:6)

这是您的代码,用于计算letterFrequency: -

letterFrequency = (letterOccurence / numberCharacters) * 100.0;

只需将上述代码更改为: -

letterFrequency = letterOccurence * 100.0 / numberCharacters;

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

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