Click here to Skip to main content
15,895,777 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Example of input :
Lucy came to Berlin, Germany in 2000.

Output:
Lucy stays in Berlin for 20 years. Berlin is in Germany.


What I have tried:

Java
import java.util.Scanner;

public class MiniTranslator {
	public static void main(String[] args) {
		//Declaring scanner
		Scanner keyboard = new Scanner(System.in);
		//Printing greeting message
		System.out.println("-------------------------------------------------------\n" + "\tLanguage Translator Program\n" +"---------------------------------------------------------");
		System.out.println("Please enter the input sentence : \n");
		String message = keyboard.next();
		String[] arr = message.split("[ ,.]+",7);
		String name = arr[0];
		String city = arr[3];
		String country = arr[4];
		String year = arr[5];
		int noOfYears =2020 - (Integer.parseInt(year));
		System.out.println(name +" stays in" +city +" for" + noOfYears +" years. " 
		                        + city +" is in" + country );
		keyboard.close();
                //which gives an error
	}
}
Posted
Updated 3-Oct-20 21:37pm
v5
Comments
OriginalGriff 4-Oct-20 1:51am    
"//which gives an error"
What error?
What's the message?

You've limited the user to one type of sentence; and can't even tell when it's wrong.

You may just as well prompt individually for a name, city, country and year. You can then apply some sort of validation.
 
Share this answer
 
Java
String year = arr[5];

The year item is not index 5. Try counting the words in the sentence to get the correct offset. But as Gerry says, this will only work for a specific sentence format.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900