2012-11-27 42 views
1

我正在做一個項目,這部分程序無法正常工作。它要求輸入字符,然後它讀取給定的文本文件,並輸出文本文件中出現的該字母的百分比。下面的代碼:Java程序打印出0而不是百分比

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; 

回答

6

這是你的代碼計算letterFrequency: -

letterFrequency = (letterOccurence/numberCharacters) * 100.0; 

只需更改上面的代碼: -

letterFrequency = letterOccurence * 100.0/numberCharacters; 

在第一代碼: - (letterOccurence/numberCharacters)將首先被評估,因爲這是一個integer division,其結果將是0,如果numerator小於denominator

要使它成爲floating-point division,只需在dividing之前將分子乘以100.0即可。