Aramza Aramza - 1 month ago 16
Java Question

Java: Finding Percent Difference

I am trying to figure out how to find the percent difference between the original (no space) string of text and the disemvoweled (no space) string of text. I am attempting to do this by using the equation ((newAmount-reducedAmount)/reducedAmount) but I am having no luck and am ending up with a value of zero, as shown below.

Thank you!

My Code:

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 + "%");

}
}


My output: (Test string is without quotes: "Testing please")

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%

Answer

You used an integer data type while calculating percentage difference while performing integer division. You need to type cast one of the variables on the right hand side of the equation to perform double division and then store them in double. The reason for doing this is java integer type can't hold the real numbers. Also, multiple it by 100 to get the percentage.

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

If you want a fraction between 0 and 1, then

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