In: Computer Science
Working in a technical field can be confusing because of all the acronyms. For example, CPU means Central Processing Unit, HDMI means High-Definition Multimedia Interface, and SMART means Self-Monitoring Analysis and Reporting Technology. Wouldn’t it be nice if there was a way to translate all these acronyms automatically?
Create a new file named Translate.java that contains the following method:
public static String expandAll(String[] acronyms, String[] definitions, String text)
This method should replace every instance of an acronym in the text with its corresponding definition. For example, expandAll({"JMU", "CS"}, {"James Madison University", "Computer Science"}, "JMU CS rocks!") would return the string “James Madison University Computer Science rocks!”.
You may assume that the two arrays will be the same length. You may also assume that the text will be reasonable English with correct grammar. In particular, there will be only one space between each word. Each sentence will either end with a space or a newline character. Punctuation not at the end of the sentence will always be followed by whitespace (i.e., you should be able to handle “Hi, Mom” but you won’t have to handle “Hi,Mom”).
Be careful not to replace acronyms in the middle of a word. For example, the string “CS uses MACS!” should expand to “Computer Science uses MACS!”, not “Computer Science uses MAComputer Science!”. You might find it helpful to use a Scanner to process the string one word at a time.
Here is the answer..
CODE:
import java.util.*;
class Translate
{
static String expandAll(String []acronyms,String
[]definitions,String text)
{
String []text_arr=text.split("
");
String s="";
for(int
i=0;i<text_arr.length;i++)
{
int
flag=0,index=0;
for(int
j=0;j<acronyms.length;j++)
{
if(text_arr[i].equals(acronyms[j]))
{
flag=1;
index=j;
}
}
if(flag==1)
{
s+=definitions[index]+" ";
}
else
s+=text_arr[i]+" ";
}
return s;
}
public static void main(String[] args) {
String []acronyms ={"JMU",
"CS"};
String []definitions={"James
Madison University", "Computer Science"};
System.out.println(expandAll(acronyms,definitions, "CS uses
MACS!"));
}
}
OUTPUT:
If you have any doubts please COMMENT..
if you understand the answer please give THUMBS UP....