Java:寻找百分比差异

时间:2016-10-27 03:02:32

标签: java for-loop percentage difference

我试图弄清楚如何找到原始(无空格)文本字符串和文本(无空格)文本字符串之间的百分比差异。我试图通过使用等式((newAmount-reducedAmount)/ reducedAmount)来做到这一点,但我没有运气,最终得到的值为零,如下所示。

谢谢!

我的代码:

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 个答案:

答案 0 :(得分:1)

在执行整数除法时,您使用整数数据类型计算百分比差异。您需要在等式右边键入一个变量来执行双重除法,然后将它们存储为double。这样做的原因是java整数类型不能保存实数。 此外,将它乘以100以获得百分比。

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

如果你想要一个0到1之间的分数,那么

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

答案 1 :(得分:-1)

您的公式为您提供0到1之间的值。

整数不能保持分数,因此它总是显示为零。

乘以100得到常规百分比值。

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