Re: Converting int to string
- From: "Rhino" <no.offline.contact.please@xxxxxxxxxx>
- Date: Sat, 29 Oct 2005 14:39:40 -0400
"Nick" <nickmacdonaldw@xxxxxxxxxxx> wrote in message
news:1130603754.443476.147260@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> Can anyone tell me how to develop this so that it shows the months ie
> January, February etc when it runs.
>
> class DayCounter {
> public static void main(String[] arguments) {
> int yearIn = 2004;
> int monthIn = 1;
> if (arguments.length > 0)
> monthIn = Integer.parseInt(arguments[0]);
> if (arguments.length > 1)
> yearIn = Integer.parseInt(arguments[1]);
> System.out.println(monthIn + "/" + yearIn + "has " + countDays(monthIn,
> yearIn) + " days.");
> }
>
> static int countDays(int month, int year) {
> int count = -1;
> switch (month) {
> case 1:
> case 3:
> case 5:
> case 7:
> case 8:
> case 10:
> case 12:
> count = 31;
> break;
> case 4:
> case 6:
> case 9:
> case 11:
> count = 30;
> break;
> case 2:
> if (year % 4 == 0)
> count = 29;
> else
> count = 28;
> if ((year % 100 == 0) & (year % 400 != 0))
> count = 28;
> }
> return count;
> }
> }
>
As it happens, I developed a simple static method to do exactly what you
want a few years back. Here's the code:
----------------------------------------------------------------------------
-----------------
/**
* Method getMonthEnglish() returns the full English month name
corresponding to
* a 0-based month number.
*
* @since 2003
*
* @return the English month name for a given 0-based month number
*/
static public String getMonthEnglish(int monthNumber) {
String[] MONTH_NAMES_ENGLISH = { "January", "February",
"March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" };
return MONTH_NAMES_ENGLISH[monthNumber];
}
----------------------------------------------------------------------------
-----------------
To invoke this method, just imitate this example:
int monthNumber = 0;
String monthName = getMonthEnglish(monthNumber);
System.out.println("Month number = " + monthNumber + "; Month name = " +
monthName);
All of this assumes that you are only concerned with English month names;
better code would look up the month name based on Locale so that month 0
would be 'janvier' in French, 'januar' in German, etc.
Rhino
.
- Follow-Ups:
- Re: Converting int to string
- From: Nick
- Re: Converting int to string
- References:
- Converting int to string
- From: Nick
- Converting int to string
- Prev by Date: Re: Converting int to string
- Next by Date: Re: help please
- Previous by thread: Re: Converting int to string
- Next by thread: Re: Converting int to string
- Index(es):