首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java:找到百分之差

问Java:找到百分之差
EN

Stack Overflow用户
提问于 2016-10-27 03:02:32
回答 2查看 7.9K关注 0票数 1

我试图找出如何找到原始(无空格)文本字符串与已删除(无空格)文本字符串之间的百分比差异。我试图通过使用等式( no挂载-还原/reducedAmount)来实现这一点,但是我没有运气,最终得到的值为零,如下所示。

谢谢!

我的守则:

代码语言:javascript
复制
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 + "%");

    }
}

我的输出:(测试字符串没有引号:“测试请”)

代码语言:javascript
复制
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%
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-10-27 03:08:24

在执行整数除法时计算百分比差时使用了整数数据类型。您需要在方程的右边键入cast变量之一以执行双除法,然后将它们存储在double中。这样做的原因是java整数类型无法保存实数。另外,乘以100就可以得到百分比。

代码语言:javascript
复制
double reductionRate = 100 * ((newAmount - reducedAmount) / (double)reducedAmount);

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

代码语言:javascript
复制
double reductionRate = ((newAmount - reducedAmount) / (double)reducedAmount);
票数 4
EN

Stack Overflow用户

发布于 2016-10-27 03:06:24

你的公式给出了一个介于0到1之间的值。

整数不能容纳分数,所以它总是显示零。

乘以100得到一个有规律的百分比值。

代码语言:javascript
复制
int reductionRate = 100*(newAmount - reducedAmount) / reducedAmount; // Percentage of character reduction
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40275410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档