2016-10-27 172 views
0

我想弄清楚如何找到原始(無空格)字符串文本和disemvoweled(無空格)字符串文本之間的百分比差異。我試圖通過使用公式((newAmount-reducedAmount)/ reducedAmount)來做到這一點,但我沒有運氣,並以零結束,如下所示。Java:查找百分比差

謝謝!

我的代碼:

import java.util.Scanner; 

public class Prog5 { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     Scanner console = new Scanner(System.in); 

     System.out.println("Welcome to the disemvoweling utility!"); // Initially typed "disemboweling" xD 
     System.out.print("Enter text to be disemvoweled: "); 
     String inLine = console.nextLine(); 
     String vowels= inLine.replaceAll("[AEIOUaeiou]", ""); // RegEx for vowel control 
     System.out.println("Your disemvoweled text is: " + vowels); // Prints disemvoweled text 

    // Used to count all characters without counting white space(s) 
    int reducedAmount = 0; 
    for (int i = 0, length = inLine.length(); i < length; i++) { 
     if (inLine.charAt(i) != ' ') { 
      reducedAmount++; 
     } 
    } 

    // newAmount is the number of characters on the disemvoweled text without counting white space(s) 
    int newAmount = 0; 
    for (int i = 0, length = vowels.length(); i < length; i++) { 
     if (vowels.charAt(i) != ' ') { 
      newAmount++; 
     } 
    } 

    int reductionRate = ((newAmount - reducedAmount)/reducedAmount); // Percentage of character reduction 


    System.out.print("Reduced from " + reducedAmount + " to " + newAmount + ". Reduction rate is " + reductionRate + "%"); 

    } 
} 

我的輸出:(測試字符串是不帶引號: 「測試請」)

Welcome to the disemvoweling utility! 

Enter text to be disemvoweled: Testing please 

Your disemvoweled text is: Tstng pls 

Reduced from 13 to 8. Reduction rate is 0% 
+2

因爲你使用'int',請改變'INT reductionRate =((newAmount - reducedAmount)/ reducedAmount); 'to'dobule reductionRate =((double)(newAmount - reducedAmount)/ reducedAmount); ' – BlackMamba

回答

0

您在執行整數除法時計算百分比差異時使用了整數數據類型。您需要輸入等式右側的一個變量來執行雙重除法,然後將它們存儲爲雙精度。這樣做的原因是java整數類型不能容納實數。 此外,多100它得到的百分比。

double reductionRate = 100 * ((newAmount - reducedAmount)/(double)reducedAmount); 

如果要在0和1之間的分數,然後

double reductionRate = ((newAmount - reducedAmount)/(double)reducedAmount); 
+1

我空出來,並沒有放在一起只乘以-100,我應該休息一下,而不是沮喪。不過謝謝你,這很有道理! – Aramza

-1

你的配方給你零和一之間的值。

整數不能容納分數,因此它總是顯示零。

乘以100得到正常的百分比值。

int reductionRate = 100*(newAmount - reducedAmount)/reducedAmount; // Percentage of character reduction 
+2

reductionRate應該是一個雙重權利? –

+0

@NirajPatel爲什麼它應該是一個雙?如果他想要一個0到100之間的舍入數字,它不一定是一個雙精度數。 OP表示對小數部分不感興趣。 –