Answer the question
In order to leave comments, you need to log in
How to combine words in a collection?
Yes, here is the assignment:
1) Create a class MyTranslator with private field dictionary of HashMap
type. Add method addNewWord(String en, String ru), which add to dictionary new
word in two languages.
2) Add a new method translate(String en) which take some string in English, and returns
its translation in Russian as the value of the type String.
3) Create a class Main with a main() method. Add to method main() code creates
an instance of MyTranslator. Add code to fill MyTranslator with few en-rus words pair
by invoking addNewWord() method.
For example:
“cat”, “cat”
“mouse”, “mouse”
public class MyTranslator {
private HashMap<String, String> dictionary;
public MyTranslator(HashMap<String, String> dictionary) {
this.dictionary = dictionary;
}
@Override
public String toString() {
return dictionary + "";
}
public MyTranslator() {
dictionary = new HashMap<>();
}
public void addNewWord(String en, String ru) {
dictionary.put(en, ru);
}
public String translate(String en) {
for (Map.Entry<String, String> d : dictionary.entrySet())
System.out.print(d.getValue() + " ");
return en;
}
}
4) Add code to read string from console and pass it into translate method. print result to
console.
5) Execute the program.
The program output must be like next example:
cat caught
mouse
Answer the question
In order to leave comments, you need to log in
Good evening.
1) You have a problem here:
public String translate(String en) {
for (Map.Entry<String, String> d : dictionary.entrySet())
System.out.print(d.getValue() + " ");
return en;
}
Add a new method translate(String en) which take some string in English, and returns
its translation in Russian as the value of the type String.
public MyTranslator(HashMap<String, String> dictionary) {
this.dictionary = dictionary;
}
how to write the translate method correctly so that it finds the word in the dictionary, combines it with others and displays it in the console, as indicated in the task?
public String translate(String en) {
return this.dictionary.get(en);
}
Add code to read string from console and pass it into translate method. print result to
console.
Scanner, System.in
public String translate(String en) {
return Arrays.stream(en.split(" ")) // создаем стрим из массива. Массив - строка разбитая по пробелам
.map(dictionary::get) // Мапим каждый элемент из коллекции dictionary
.collect(Collectors.joining(" ")); // собираем стрим в одну строку, прибавляя пробел между элементами
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question