DwemerTech DwemerTech - 1 month ago 6
Java Question

Do while loop to delete characters until count is achieved not working Java

I'm trying to make this do while loop delete vowels from a string until the correct character count is reached (140), however it is not working. I'm unsure if the do while loop is working then stopping once the condition is met but if that is the case how can I run the rest of my code once the condition is met?
Thanks in advance!
Here is the code I am using:

public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Enter the phrase to be shortened: ");
String toCompress = scan.nextLine();
int length = toCompress.length();
System.out.println(length);;

do {
toCompress = toCompress.replaceAll("[AEIOUaeiou]", "");
}while(length >= 140);


System.out.println("Compressed phrase: ");
System.out.println(toCompress);
int length2 = toCompress.length();
System.out.print(length2);;
scan.close();

}

Answer

I've figured out a better way to do this:

public static void main(String[] args)
{
    Random RNG = new Random(); //Set up the RNG
    Scanner scan = new Scanner( System.in ); //Set up the scanner
    System.out.println("Enter the phrase to be shortened: ");
    String toCompress = scan.nextLine();
    //Setup the string builder with the user input
    StringBuilder shorten = new StringBuilder(toCompress); 

    //Wile the length is greater than or equal to 140,do some conversions then 
    //run the if statement
    while (shorten.length() >= 140)
    {
        int randChar = RNG.nextInt(shorten.length());
        char convertToChar = shorten.charAt(randChar);
        int convertToInt = (int)convertToChar;

        //If statement choosing which ASCII chars to delete (vowels)
            if ((convertToInt > 32) || (convertToInt == 65)
                    || (convertToInt == 69) || (convertToInt == 73)
                    || (convertToInt == 79) || (convertToInt == 85))
                        {
                            shorten.deleteCharAt(randChar);
                        }
    }
    System.out.println("Compressed phrase:");
    System.out.println(shorten);
    System.out.println(shorten.length());

    scan.close();   
}}