In: Computer Science
In this question, you are asked to write a simple java program to understand natural language.
The user will enter the input following the format: Name came to City, Country in Year.
For example: Robin came to Montreal, Canada in 2009. Assume a perfect user will follow the exactly above formats for the inputs.
Your program should be able to analyze the key words (Name, City, Country and Year) from the inputs and reorganize the outputs following format: Name stay in City for X year(s). City is in Country.
For example Robin stay in Montreal for 11 years. Montreal is in Canada.
* Please note X = 2020-Year.
Here is an example of the output to illustrate the expected behavior of your program.
Please enter the input sentence (press q to exit): Robin came to Vancouver, Canada in 2009.
Output: Robin stays in Montreal for 11 years. Montreal is in Canada.
Explanation:I have written the NaturalLanguage class that accepts and natural language and prints the output in the given format.I have also shown the output of the program, please find the image attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation.
//code starts
import java.util.Scanner;
public class NaturalLanguage {
public static void main(String[] args) {
Scanner input = new
Scanner(System.in);
String sentence = "";
while (true) {
System.out.print("Please enter the input sentence (press q to
exit):");
sentence =
input.nextLine();
if
(sentence.equals("q"))
break;
String words[] =
sentence.split(" ");
String name =
words[0];
String city =
words[3].substring(0, words[3].length() - 1);
int years = 2020
- Integer.parseInt(words[6].substring(0, words[6].length() -
1));
String country =
words[4];
System.out.println("Output: " + name + " stays in " + city + " for
" + years + " years. " + city + " is in "
+ country + ".");
}
input.close();
}
}
Output: