c# read the number of month and output the name of month - c#

Im trying to write a C# console program to read in the number of a month and output the name of the month, and then ask the user if they want to know the number of days in that month and if so output the number of days. Assuming that there are no leap years and February ALWAYS has 28 days only.
Thanks in advance if anyone can help!!
EDIT:
This is what I have so far, I'm having trouble with the second half of the problem, I'm not sure how to ask the user if they want to know the days of the month and how to use a switch to output the number of days...
class MainClass
{
public static void Main (string[] args)
{
{
Console.WriteLine("Give me an integer between 1 and 12, and I will give you the month");
int monthInteger = int.Parse(Console.ReadLine());
DateTime newDate = new DateTime(DateTime.Now.Year, monthInteger, 1);
Console.WriteLine("The month is: " + newDate.ToString("MMMM"));
Console.WriteLine();

A simple switch case will do?
string input = Console.In.ReadLine();
int number = -1;
int.TryParse(input, out number);
switch (number)
{
case 1:
Console.Out.WriteLine("January");
break;
case 2:
Console.Out.WriteLine("February");
break;
case -1:
Console.Out.WriteLine("Please input a valid number");
break;
default:
Console.Out.WriteLine("There are only 12 months in a year");
break;
}
i take it this is enough to finish the rest of your code.
next time, please provide some code for what you have tried already, just asking for simple code usually gets you nowhere.

public static string getName(int i)
{
string[] names = { "jan", "feb", ... } // fill in the names
return names[i-1];
}

public static string getMonthName(int mounth)
{
DateTime dt = new DateTime(2000, mounth, 1);
return dt.ToString("M").Substring(0, dt.ToString("M").IndexOf(' '));
}

Based on your other related question that was closed as a duplicate of this one (https://stackoverflow.com/questions/24996241/c-sharp-number-of-days-in-a-month-using-a-switch#24996339)...
This is clearly an academic exercise that wants you to learn about the switch statement.
Here is a complete example that demonstrates a couple ways to do switch statements. Since you already grabbed the month number from the user you can switch on that value by creating a mapping between the month and the number of days in the month.
To wit:
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Give me an integer between 1 and 12, and I will give you the month");
int monthInteger = int.Parse(Console.ReadLine()); // WARNING: throws exception for non-integer input
Console.WriteLine(GetMonthName(monthInteger));
Console.WriteLine();
Console.Write("Display days in month (y/n)? ");
if (Console.ReadLine() == "y")
{
int daysInMonth = GetDaysInMonth_NoLeapYear(monthInteger);
if (daysInMonth > 0)
{
Console.WriteLine(String.Format("{0} days in {1}",
daysInMonth.ToString(),
GetMonthName(monthInteger)));
}
else
{
Console.WriteLine("Invalid month entered.");
}
Console.WriteLine();
}
Console.WriteLine("Hit enter to close");
Console.ReadLine();
}
private static String GetMonthName(int monthInteger)
{
DateTime newDate = new DateTime(DateTime.Now.Year, monthInteger, 1);
String monthName = newDate.ToString("MMMM");
return monthName;
}
/// <summary>
/// Prints days in month. Assumes no leap year (since no year context provided) so Feb is always 28 days.
/// </summary>
/// <param name="monthInteger"></param>
private static int GetDaysInMonth_NoLeapYear(int monthInteger)
{
int daysInMonth = -1; // -1 indicates unknown / bad value
switch (monthInteger)
{
case 1: // jan
daysInMonth = 30;
break;
case 2: // feb
daysInMonth = 28; // if leap year it would be 29, but no way of indicating leap year per problem constraints
break;
case 3: // mar
daysInMonth = 31;
break;
case 4: // apr
daysInMonth = 30;
break;
case 5: // may
daysInMonth = 31;
break;
case 6: // jun
daysInMonth = 30;
break;
case 7: // jul
daysInMonth = 31;
break;
case 8: // aug
daysInMonth = 31;
break;
case 9: // sep
daysInMonth = 30;
break;
case 10: // oct
daysInMonth = 31;
break;
case 11: // nov
daysInMonth = 30;
break;
case 12: // dec
daysInMonth = 31;
break;
}
return daysInMonth;
}
/// <summary>
/// Prints days in month. Assumes no leap year (since no year context provided) so Feb is always 28 days.
/// </summary>
/// <param name="monthInteger"></param>
private static int GetDaysInMonth_NoLeapYear_Compact(int monthInteger)
{
// uses case statement fall-through to avoid repeating yourself
int daysInMonth = -1; // -1 indicates unknown / bad value
switch (monthInteger)
{
case 2: // feb
daysInMonth = 28; // if leap year it would be 29, but no way of indicating leap year per problem constraints
break;
case 3: // mar
case 5: // may
case 7: // jul
case 8: // aug
case 10: // oct
case 12: // dec
daysInMonth = 31;
break;
case 1: // jan
case 4: // apr
case 6: // jun
case 9: // sep
case 11: // nov
daysInMonth = 30;
break;
}
return daysInMonth;
}
}
GetDaysInMonth_NoLeapYear_Compact is included only to illustrate the case fall-through behavior that lets multiple case statements go to the same code.

Related

putting 3 switches in one

I have for some time been working on a console calendar that counts on its own to a certain date with the correct day of week, date etc, which then allows you to insert data on that day. All that is done, but now I'm adding a function where you can put the dates from start date to end date into a text file. The output will be something like:
05.06.2016 Tuesday
06.06.2016 Wednesday
07.06.2016 Thursday
01.06.2016 Friday
02.06.2016 Saturday
03.01.2016 Sunday
04.01.2016 Monday
05.01.2016 Tuesday
06.01.2016 Wednesday
07.01.2016 Thursday
01.01.2016 Friday
02.01.2016 Saturday
This sent me off to this MainInputSection class of my program, and I had to add parameter so that I could alter the messages from just "Input YEAR" etc to "Input start of YEAR for file" etc.
There are now three switches right next to each other that does almost the same thing, and this section of my program therefore felt a bit simple, repetetive, and hard-coded.
What I'd like is a loop or something that shortens this stuff and makes it less nooby the way it is now in order to get the right Console.WriteLine(); matched with the correct Console.ReadLine(); to fill in the int[] arrayAnswers = { answerYear, answerMonth, answerDay }; correcly, but more professionally. I'm thinking something like a for each loop or something, but I only halfway see a solution like that and I need help.
public class MainInputSection
{
public static int[] GetUserInputDate(string mode)
{
int answerYear;
int answerMonth;
int answerDay;
Console.ForegroundColor = ConsoleColor.Cyan;
switch (mode)
{
case "calender":
Console.WriteLine("Input YEAR");
break;
case "fileStart":
Console.WriteLine("Input start of YEAR for file");
break;
case "fileEnd":
Console.WriteLine("Input end of YEAR for file");
break;
}
Console.ResetColor();
answerYear = Convert.ToInt32(Console.ReadLine());
Console.ForegroundColor = ConsoleColor.Cyan;
switch (mode)
{
case "calendar":
Console.WriteLine("Input MONTH");
break;
case "fileStart":
Console.WriteLine("Input start of MONTH for file");
break;
case "fileEnd":
Console.WriteLine("Input end of MONTH for file");
break;
}
Console.ResetColor();
answerMonth = Convert.ToInt32(Console.ReadLine());
Console.ForegroundColor = ConsoleColor.Cyan;
switch (mode)
{
case "calendar":
Console.WriteLine("Input DAY");
break;
case "fileStart":
Console.WriteLine("Input start of DAY for file");
break;
case "fileEnd":
Console.WriteLine("Input end of DAY for file");
break;
}
Console.ResetColor();
answerDay = Convert.ToInt32(Console.ReadLine());
int[] arrayAnswers = { answerYear, answerMonth, answerDay };
return arrayAnswers;
}
}
So what you have to do is, group the common things together inside a method, here all cases should display some text in the console with a color and then call the reset color option, and store the user input to an integer variable. So group them together inside a method and return the integer value from the method. I think the signature of the method should be like the following:
public static int GetInput(string displayMessage)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(displayMessage);
Console.ResetColor();
return int.Parse(Console.ReadLine());
}
And you can use the method like the following:
public static int[] GetUserInputDate(string mode)
{
int answerYear = 0;
int answerMonth = 0;
int answerDay = 0;
switch (mode)
{
case "calender":
answerYear = GetInput("Input YEAR");
answerMonth = GetInput("Input MONTH");
answerDay = GetInput("Input DAY");
break;
case "fileStart":
answerYear = GetInput("Input start of YEAR for file");
answerMonth = GetInput("Input start of MONTH for file");
answerDay = GetInput("Input start of DAY for file");
break;
case "fileEnd":
answerYear = GetInput("Input end of YEAR for file");
answerMonth = GetInput("Input end of MONTH for file");
answerDay = GetInput("Input end of DAY for file");
break;
}
int[] arrayAnswers = { answerYear, answerMonth, answerDay };
return arrayAnswers;
}

Condition base on Week of year (weekly changing method)

Im going to deploy some conditional method that changed weekly.
for example This is my old code :
DayOfWeek dow = DateTime.Now.DayOfWeek;
switch (dow)
{
case DayOfWeek.Friday:
///Do something
break;
case DayOfWeek.Monday:
///Do something
break;
case DayOfWeek.Saturday:
///Do something
break;
case DayOfWeek.Sunday:
///Do something
break;
case DayOfWeek.Thursday:
///Do something
break;
case DayOfWeek.Tuesday:
///Do something
break;
case DayOfWeek.Wednesday:
///Do something
break;
}
in above code if user calls my url in each day , it will get special answer based on that day.
now i wanna make another method like this :
Condition week 1
{
//function 1
}
Condition Week 2
{
//function 2
}
Condition Week 3
{
//function 3
}
Condition Week 4
{
//function 1
}
Condition Week 5
{
//function 2
}
..........
as u can see after week 3 i start to run/loop function 1 from start till week 6 , and this will continue
till end of year and after that.
should i achieve this goal by using "Calendar.GetWeekOfYear" ?
or should i use this method? :
DateTime myDT = DateTime.Now;
GregorianCalendar myCal = new GregorianCalendar();
if ((myCal.GetDayOfMonth(myDT) >= 1) && (myCal.GetDayOfMonth(myDT) < 8))
{
Function 1
}
else if ((myCal.GetDayOfMonth(myDT) >= 8) && (myCal.GetDayOfMonth(myDT) < 15))
{
Function 2
}
else if ((myCal.GetDayOfMonth(myDT) >= 15) && (myCal.GetDayOfMonth(myDT) < 22))
{
Function 3
}
else if ((myCal.GetDayOfMonth(myDT) >= 22) && (myCal.GetDayOfMonth(myDT) < 31))
{
Function 1
}
Use GetWeekOfYear. It gives you some nice flexibility, how the first week is defined, and what the first day of the week should be. Here's the MSDN documentation.
class Program
{
static void Main(string[] args)
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar calendar = dfi.Calendar;
var week = calendar.GetWeekOfYear(DateTime.Now.AddDays(1), CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
Console.Write(week);
Console.ReadLine();
}
}

Why won't my c# application work? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This program is supposed to get you a garfield comic from the date you entered or the daily comic. The first button should allow you to pick a custom comic but only the daily comic (button 2) seems to work Here's the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Garfield_Comic_Viewer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int month = int.Parse(textBox1.Text);
int day = int.Parse(textBox2.Text);
int year = int.Parse(textBox3.Text);
switch (month)
{
case 1:
month = 01;
break;
case 2:
month = 02;
break;
case 3:
month = 03;
break;
case 4:
month = 04;
break;
case 5:
month = 05;
break;
case 6:
month = 06;
break;
case 7:
month = 07;
break;
case 8:
month = 08;
break;
case 9:
month = 09;
break;
}
switch (day)
{
case 1:
day = 01;
break;
case 2:
day = 02;
break;
case 3:
day = 03;
break;
case 4:
day = 04;
break;
case 5:
day = 05;
break;
case 6:
day = 06;
break;
case 7:
day = 07;
break;
case 8:
day = 08;
break;
case 9:
day = 09;
break;
}
pictureBox1.ImageLocation = ("http://garfield.com/uploads/strips/" +year+ "-" +month+ "-" + day + ".jpg");
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
string mon = DateTime.Now.ToString("MM");
string d = DateTime.Now.ToString("dd");
string y = DateTime.Now.ToString("yyyy");
pictureBox1.ImageLocation = "http://garfield.com/uploads/strips/" + y + "-" + mon + "-" + d + ".jpg";
DateTime whole = DateTime.Now;
}
}
}
The problem is you're expecting integers to behave like strings.
The point you're missing is that:
int a = 01;
is the same as:
int a = 1;
There's no difference. You can't pad an integer. What you need is to format the integers into a string, using a format specifier. Something like this:
pictureBox1.ImageLocation =
string.Format("http://garfield.com/uploads/strips/{0:D4}-{1:D2}-{2:D2}.jpg",
year, month, day);
This will give a string that contains the numbers in the format yyyy-mm-dd.
(The documentation for padding string-formatted integers is here.)

Month in c# using DateTime

I am wondering if there is way to have the user enter a number like 01 and have that string converted to the month using dateTime. I know how to have the user enter a string such as 01/01/2011 and have the converted to a DateTime. Is there a way to use datetime to convert a two number string into a month. Something like this, but that would work
Console.WriteLine("Please the month numerically");
string date = Console.ReadLine();
dt = Convert.ToDateTime(date).Month;
You could probably get it jumping through some hoops with DateTime, however;
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(int monthNumber);
is probably easier.
It is already built into the .NET framework: see System.Globalization.DateTimeFormatInfo.MonthNames
It'd be easier to just have an array of 12 elements, each being a month.
String[] Months = new String[] {"Jan", "Feb"}; //put all months in
Console.WriteLine("Please the month numerically");
string date = Console.ReadLine();
int index = 0;
if (!int.TryParse(date, out index)) {
// handle error for input not being an int
}
dt = Months[index];
If you really wanted to stick with using the DateTime class, you could take in the month and then tag on some day and year and use the method you provided in your code. For example...
dt = Convert.ToDateTime(date + "/01/2012").Month;
But this is less advised.
Your example is not complete, cause you need to specify which year and which day in the date.
Assuming that that data have to be of the current date, you can do something like this:
DateTime dt = new DateTime(DateTime.Now.Year, int.Parse("01"), DateTime.Now.Day);
Don't forget, obviously, add a couple of controls, like
Month range {1-12}
Month string is a number
EDIT
int month =-1;
if(int.TryParse(userInputString, out month)){
if(month>=1 && month <=12) {
DateTime dt = new DateTime(
DateTime.Now.Year,
month,
DateTime.Now.Day);
}
}
Hope this helps.
public static string ReturnMonthName(string pMonth)
{
switch (pMonth)
{
case "01" :
return "January";
case "02":
return "February";
case "03":
return "March";
case "04":
return "April";
case "05":
return "May";
case "06":
return "June";
case "07":
return "July";
case "08":
return "August";
case "09":
return "September";
case "10":
return "October";
case "11":
return "November";
case "12":
return "December";
default:
return "Invalid month";
}
Strip the month from your datetime and use a switch/case select to assign your variable.
switch (val)
{
case 1:
MessageBox.Show("The day is - Sunday");
break;
case 2:
MessageBox.Show("The day is - Monday");
break;
case 3:
MessageBox.Show("The day is - Tuesday");
break;
case 4:
MessageBox.Show("The day is - wednesday");
break;
case 5:
MessageBox.Show("The day is - Thursday");
break;
case 6:
MessageBox.Show("The day is - Friday");
break;
case 7:
MessageBox.Show("The day is - Saturday");
break;
default:
MessageBox.Show("Out of range !!");
break;
}

How to get the month name in C#?

How does one go about finding the month name in C#? I don't want to write a huge switch statement or if statement on the month int. In VB.Net you can use MonthName(), but what about C#?
You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.
I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.
Here is an example of how to do it using extension methods:
using System;
using System.Globalization;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToMonthName());
Console.WriteLine(DateTime.Now.ToShortMonthName());
Console.Read();
}
}
static class DateTimeExtensions
{
public static string ToMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
}
public static string ToShortMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
}
}
Hope this helps!
Use the "MMMM" format specifier:
string month = dateTime.ToString("MMMM");
string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now)
Supposing your date is today. Hope this helps you.
DateTime dt = DateTime.Today;
string thisMonth= dt.ToString("MMMM");
Console.WriteLine(thisMonth);
If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime
//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);
private string MonthName(int m)
{
string res;
switch (m)
{
case 1:
res="Ene";
break;
case 2:
res = "Feb";
break;
case 3:
res = "Mar";
break;
case 4:
res = "Abr";
break;
case 5:
res = "May";
break;
case 6:
res = "Jun";
break;
case 7:
res = "Jul";
break;
case 8:
res = "Ago";
break;
case 9:
res = "Sep";
break;
case 10:
res = "Oct";
break;
case 11:
res = "Nov";
break;
case 12:
res = "Dic";
break;
default:
res = "Nulo";
break;
}
return res;
}

Categories