Respuesta :
Answer:
Scanner scan = new Scanner(System.in);
System.out.println("Type the message to be shortened");
String msg = scan.nextLine();
System.out.println();
msg = msg.toLowerCase();
String newStr = "";
System.out.println("Algorithm 1");
int vowels = 0;
int repeats = 0;
for(int i = 0; i < msg.length(); i++)
{
if((msg.substring(i, i +1).equals("a") || msg.substring(i, i+1).equals("e") || msg.substring(i, i +1).equals("i") || msg.substring(i, i+1).equals("o") || msg.substring(i, i +1).equals("u")))
{
if(i != 0 && !msg.substring(i -1, i).equals(" "))
{
vowels++;
}
else
newStr += msg.substring(i, i +1);
}
else if(i != 0 && msg.substring(i, i +1).equals(msg.substring(i -1, i)))
{
repeats++;
}
else
{
newStr += msg.substring(i, i +1);
}
}
System.out.println("\nAlgorithm 1");
System.out.println("Vowels removed: " + vowels);
System.out.println("Repeats removed: " + repeats);
System.out.println("Algorithm 1 message: " + newStr);
System.out.println("Algorithm 1 characters saved: " + (vowels + repeats));
algorithm2(msg);
}
public static void algorithm2(String msg)
{
String alg2Msg = "";
int uniqueLetters = 0;
// Iterate through each letter in msg
for(int i=0; i < msg.length(); i++)
{
String ltr = msg.substring(i,i+1);
// Only process if this character is not a space
if(!ltr.equals(" "))
{
/* Check whether this character has already appeared by
* iterating through characters from start up to the current
* letter and using a boolean flag variable.
*/
boolean alreadyUsed = false;
for(int j=0; j<i; j++)
{
if(msg.substring(j,j+1).equals(ltr))
{
alreadyUsed = true;
}
}
/* If this character hasn't already appeared,
* iterate through the rest of the characters
* and count how many times it appears.
*/
if(!alreadyUsed)
{
uniqueLetters++;
int count = 0;
for(int j=i; j<msg.length(); j++)
{
if(msg.substring(j,j+1).equals(ltr))
{
count++;
}
}
alg2Msg += count + ltr;
}
}
} //end for loop
System.out.println("\nAlgorithm 2");
System.out.println("Unique characters found: " + uniqueLetters);
System.out.println("Algorithm 2 message: " + alg2Msg);
System.out.println("Algorithm 2 characters saved: " + (msg.length() - alg2Msg.length()));
} //end algorithm2
}
Explanation:
Here you go!