11356 – Dates UVA Solution

This is an easy problem from uva judge http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=2341

Adhoc. I solve this problem using Java GregorianCalendar class.

How I did it

  • Read the number of cases.
  • Init an array of months.
  • Read the date to process.
  • Read the days to add.
  • Init a GregorianCalendar object with the day, month and year of the input.
  • Add the days to the GregorianCalendar object.
  • Print the answer

Hints

  • Gregorian Calendar manage the month in this way. January = 0, February = 1 and so on.
  • Gregorian Calendar manage the leap year. I do not care how it does, but it does.
  • Careful with days less than 10 in the output, Check the output example

Code

import java.util.*;
public class Dates11356 {

	public static void main(String[]args)
	{	
		String[] monthArray = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

		String currentDate;
		String[] dateParts;
		int casos, cDay, cMonth=0, cYear, traverseDays;

		Scanner lee = new Scanner(System.in);
		casos = lee.nextInt();

		for(int a=1; a<=casos; a++)
		{
			currentDate = lee.next();
			traverseDays = lee.nextInt();

			dateParts = currentDate.split("-");
			cDay = Integer.parseInt(dateParts[2]);
			cYear = Integer.parseInt(dateParts[0]);
			for(int x=0; x<12; x++)
				if(monthArray[x].equals(dateParts[1]))
				{
					cMonth = x;
					break;
				} 	

			Calendar myCalendar = new GregorianCalendar(cYear, cMonth, cDay);
			myCalendar.add(Calendar.DATE , traverseDays);

			int year = myCalendar.get(Calendar.YEAR);
			int day  = myCalendar.get(Calendar.DATE);
			String month = monthArray[myCalendar.get(Calendar.MONTH)];
			//Case 1: 1985-January-01
			//System.out.printf("Case %d: %d-%s-%02d\n", a, year, month, day);//Formatear Para que tenga un 0 por delante if dia <10
			System.out.print("Case " + a + ": " + year + "-" + month + "-");
			if(day<10)
			  System.out.println("0" + day);
			else
				System.out.println(day);
		}
	}
}

Leave a comment