An acronym is a word formed from the initial letters of words in a set phrase. Define a method named createAcronym that takes a string parameter and returns the acronym of the string parameter. Append a period (.) after each letter in the acronym. If a word begins with a lower case letter, don't include that letter in the acronym. Then write a main program that reads a phrase from input, calls createAcronym() with the input phrase as argument, and outputs the returned acronym. Assume the input has at least one upper case letter.
Ex: If the input is:
Institute of Electrical and Electronics Engineers
the output should be:
I.E.E.E.
Ex: If the input is:
Association for computing MACHINERY
the output should be:
A.M.
The letters ACHINERY in MACHINERY don't start a word, so those letters are omitted.
The program must define and call a method:
public static String createAcronym(String userPhrase)
So far my code looks like this:
import java.util.Scanner;
public class LabProgram {
public static String createAcronym(String userPhrase) {
String[] separatedWords = userPhrase.split(" ");
String acronymAlphabets = " ";
for(int i = 0; i < separatedWords.length; ++i) {
if(Character.isUpperCase(separatedWords [i].charAt(0))) {
acronymAlphabets += Character.toUpperCase(separatedWords [i].charAt(0));
}
}
return acronymAlphabets;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println(createAcronym(userInput.nextLine()));
}
}
The system returns the correct acronym but cant for the life of me figure out how to get the periods in the proper place. Side note: Im really good at getting them at the beginning or end of them. Any help "appending" this problem would be awesome!
Change
acronymAlphabets += Character.toUpperCase(separatedWords [i].charAt(0));
to
acronymAlphabets += Character.toUpperCase(separatedWords [i].charAt(0))+".";
Here is one way using streams.
String[] titles = {"Institute of Electrical and Electronics Engineers",
"Association for Computing MACHINERY",
"Association of Lions, and Tigers, and Bears, oh my!!"};
for (String title : titles) {
System.out.println(createAcronym(title));
}
prints
I.E.E.E
A.C.M
A.L.T.B
public static String createAcronym(String title) {
return Arrays.stream(title.split("\\W+"))
.filter(str -> Character.isUpperCase(str.charAt(0)))
.map(str -> str.substring(0, 1))
.collect(Collectors.joining("."));
}