2016-10-27 1 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 =((ダブル)(newAmount - reducedAmount)/ reducedAmount); ' – BlackMamba

答えて

0

整数除算を実行中にパーセント差を計算する際に、整数データ型を使用しました。方程式の右辺に変数のキャスト1を入力して二重除算を実行し、二重に格納する必要があります。これを行う理由は、Javaの整数型は実数を保持できません。 また、100を倍数してパーセンテージを取得します。その後、

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

あなたは0と1の間の小数をしたい場合は、

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

私は空白にして一緒にまとめて-100を乗じただけではなく、挫折せずに休憩を取っていたはずです。しかし、ありがとう、これは理にかなっています! – Aramza

-1

あなたの式はあなたに0と1の間の値を与えます。

整数は分数を保持できないため、常にゼロを示します。

通常のパーセント値を得るには100を掛けます。

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

reductionRateは二重権利ですか? –

+0

@NirajPatelなぜそれは二重にすべきですか? 0と100の間の丸められた数値が必要な場合は、doubleである必要はありません。営業利益は、小部分には関心を示さなかった。 –

関連する問題