我试图找出如何找到原始(无空格)文本字符串与已删除(无空格)文本字符串之间的百分比差异。我试图通过使用等式( no挂载-还原/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%发布于 2016-10-27 03:08:24
在执行整数除法时计算百分比差时使用了整数数据类型。您需要在方程的右边键入cast变量之一以执行双除法,然后将它们存储在double中。这样做的原因是java整数类型无法保存实数。另外,乘以100就可以得到百分比。
double reductionRate = 100 * ((newAmount - reducedAmount) / (double)reducedAmount);如果你想要0到1之间的分数,那么
double reductionRate = ((newAmount - reducedAmount) / (double)reducedAmount);发布于 2016-10-27 03:06:24
你的公式给出了一个介于0到1之间的值。
整数不能容纳分数,所以它总是显示零。
乘以100得到一个有规律的百分比值。
int reductionRate = 100*(newAmount - reducedAmount) / reducedAmount; // Percentage of character reductionhttps://stackoverflow.com/questions/40275410
复制相似问题