Having trouble with code to convert number into a month - c#

here is my source code, everything is good until i get to the output and I cant get this to work. Visual Studio doesn't like what I have in the output section, labeled //OUTPUT.
What do I need to add or change to get this to work?
static void Main(string[] args)
{
int monthNumber;
string monthName;
//INPUT
Console.WriteLine("Please enter the number of the month");
monthNumber = Convert.ToInt16(Console.ReadLine());
//PROCCESSESS
if (monthNumber == 1)
{
monthName = "January";
}
else if (monthNumber == 2)
{
monthName = "February";
}
else if (monthNumber == 3)
{
monthName = "March";
}
else if (monthNumber == 4)
{
monthName = "April";
}
else if (monthNumber == 5)
{
monthName = "May";
}
else if (monthNumber == 6)
{
monthName = "June";
}
else if (monthNumber == 7)
{
monthName = "July";
}
else if (monthNumber == 8)
{
monthName = "August";
}
else if (monthNumber == 9)
{
monthName = "September";
}
else if (monthNumber == 10)
{
monthName = "October";
}
else if (monthNumber == 11)
{
monthName = "November";
}
else if (monthNumber == 12)
{
monthName = "December";
}
//space to increase readability
Console.WriteLine(Environment.NewLine);
//OUTPUT
Console.WriteLine("Month:" + monthName);
Console.ReadLine();
}

monthName must be initialized before use. So you can change the declaration line as
string monthName = null;
That's because the code does not guarantee that monthName gets assigned. For example what if the input number is 13?

You have a lot of else if, but in the end, there's no else to cover the case where none of the if apply. Therefore the compiler can't guarantee that monthName was ever assigned. Maybe the user typed "28"?
It would look better to use a switch statement with twelve case sections and one default section.
But also, the month names are built into the framework. So with using System.Globalization; you could simply say
monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(monthNumber);
or
monthName = CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(monthNumber);
You can also get a DateTime directly from the input:
DateTime dateTime = DateTime.ParseExact(Console.ReadLine(), "%M", null);
Then
monthName = dateTime.ToString("MMMM");

a) declare a variable
b) if you are using month names, and you want some specific names, try using enum. really eazy and functional.
You can make your own setup of names/markings with your own pace of numbering those names/markings.
For Eg.
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

Related

C# Days of the week tryparse string conversions

So I am currently trying to finish this program that when you input a number correlating to the days of the week, it reflects the text connected to the numeric variable. (IE : Sunday - 1, Monday - 2, etc etc.)
I have found a functioning code that makes the program work, but it outputs incorrect information. No matter what number I put in, it always displays Sunday. And it doesn't stop me from inputting bad variables. Which I want it to. I'm frustrated at this point and I am very new to all of this. Can someone check over my code and tell me what I'm doing incorrectly? Thank you.
private void OkButton_Click(object sender, EventArgs e)
{
string day ="1";
int number;
if (int.TryParse(day, out number))
{
if (number >= 7 && number <= 1)
{
switch (day)
{
case "1":
dayOutputLabel.Text = "Sunday";
break;
case "2":
dayOutputLabel.Text = "Monday";
break;
case "3":
dayOutputLabel.Text = "Tuesday";
break;
case "4":
dayOutputLabel.Text = "Wednesday";
break;
case "5":
dayOutputLabel.Text = "Thursday";
break;
case "6":
dayOutputLabel.Text = "Friday";
break;
case "7":
dayOutputLabel.Text = "Saturday";
break;
}
}
else
{
MessageBox.Show("Invalid number input. Please use a number between 1 and 7.");
}
}
else
{
MessageBox.Show("Please put in a valid number.");
}
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
Looks like you've hard coded day = "1" (i.e. Sunday).
Also this is a mistake:
if (number >= 7 && number <= 1)
Surely you meant...
if (number >= 1 && number <= 7)
I can't tell precisely what sort of project you're working on, but the following slight modification works in wpf and should be all you need to solve this:
private void OKButton_Click(object sender, RoutedEventArgs e)
{
string day = myTextBox.Text.Trim();
int number = 0;
if (int.TryParse(day, out number))
{
if (number >= 1 && number <= 7)
{
switch (day)
{
case "1":
dayOutputLabel.Content = "Sunday";
break;
case "2":
dayOutputLabel.Content = "Monday";
break;
case "3":
dayOutputLabel.Content = "Tuesday";
break;
case "4":
dayOutputLabel.Content = "Wednesday";
break;
case "5":
dayOutputLabel.Content = "Thursday";
break;
case "6":
dayOutputLabel.Content = "Friday";
break;
case "7":
dayOutputLabel.Content = "Saturday";
break;
}
}
else
{
MessageBox.Show("Invalid number input. Please use a number between 1 and 7.");
}
As mentioned in the comment above... here is a possible solution using the System.DayOfWeek enumeration:
private void OKButton_Click(object sender, RoutedEventArgs e)
{
// this TryParse makes use of pattern matching
if(int.TryParse(myTextBox.Text.Trim(), out var input) && input >= 0 && input <= 6)
{
// this should automatically convert to the name of the day of week
// if not, add .ToString() at the end
dayOutputLabel.Content = (DayOfWeek)input;
}
else
{
MessageBox.Show(
text: "Please use a number between 0 and 6",
caption: "Invalid Input",
buttons: MessageBoxButtons.OK,
icon: MessageBoxIcon.Error);
}
}
And here is an another option using Enum.TryParse() instead:
private void OKButton_Click(object sender, RoutedEventArgs e)
{
// this TryParse makes use of pattern matching
if(Enum.TryParse(myTextBox.Text.Trim(), out DayOfWeek input) &&
input >= DayOfWeek.Sunday && input <= DayOfWeek.Saturday)
{
// this should automatically convert to the name of the day of week
// if not, add .ToString() at the end
dayOutputLabel.Content = input;
}
else
{
MessageBox.Show(
text: "Please use a number between 0 and 6",
caption: "Invalid Input",
buttons: MessageBoxButtons.OK,
icon: MessageBoxIcon.Error);
}
}

A Variable doesn't exist in the current context

(I'm a beginner and just started learning C# in college/A-level, so my code is really inefficient).
Anyway, the code below is just a part of my "CinemaBookingSystem" and because my variable filmName is declared outside of my switch case, it says that "filmName" does not do not exist in this context. I tried using the "public static string filmname = "example";" method but that won't work because I'm declaring filmname more than once inside different if statements.
if (filmNum == 1)
string filmName = "Teenage Horror Film";
if (filmNum == 2)
;
string filmName = "How I Live Now";
switch (filmNum)
{
case 1:
case 2:
if (Age >= 15)
{
Console.WriteLine("What date do you want to watch the film? (Format : dd/mm/yyyy) :");
DateTime dateChoice = DateTime.Parse(Console.ReadLine());
DateTime now = DateTime.Now;
DateTime limit = now.AddDays(7);
if (dateChoice >= now && dateChoice <= limit)
{
Console.WriteLine("--------------------");
Console.WriteLine("Aquinas Multiplex");
Console.WriteLine("Film : {0}", filmName);
Console.WriteLine("Date : {0}", dateChoice);
Console.WriteLine("--------------------");
}
else
{
Console.WriteLine("Access denied - date is invalid");
}
}
while (Age < 15)
{
Console.WriteLine("Access denied - You are too young");
}
break;
}
Kenny, since you declare variable filmName in condition statement it is not accessible in switch. You need to declare it before if:
string filmName = string.empty;
if (filmNum == 1) ;
{
filmName = "Teenage Horror Film";
}
if (filmNum == 2) ;
{
filmName = "How I Live Now";
}
switch (filmNum)
{
case 1: case 2:
if (Age >= 15)
{
Console.WriteLine("What date do you want to watch the film? (Format : dd/mm/yyyy) :");
DateTime dateChoice = DateTime.Parse(Console.ReadLine());
DateTime now = DateTime.Now;
DateTime limit = now.AddDays(7);
if (dateChoice >= now && dateChoice <= limit)
{
Console.WriteLine("--------------------");
Console.WriteLine("Aquinas Multiplex");
Console.WriteLine("Film : {0}", filmName);
Console.WriteLine("Date : {0}", dateChoice);
Console.WriteLine("--------------------");
}
else
{
Console.WriteLine("Access denied - date is invalid");
}
}
while (Age < 15)
{
Console.WriteLine("Access denied - You are too young");
}
break;
}
}
}
You need to declare it outside of the if statements and just asign the value inside (make sure there is a default value in case neither if gets triggered).
Also you have semicolons right behind your if statements.

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();
}
}

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;
}

A less ugly way to localize DayOfWeek? [duplicate]

This question already has answers here:
C# Cultures: Localize DayOfWeek?
(2 answers)
Closed 9 years ago.
using System;
namespace Server.Custom.Extensions
{
public static class FriendlyExtensions
{
public static string Friendly(this DayOfWeek day)
{
if (day == DateTime.Now.DayOfWeek)
return "Hoy";
int dayOfWeek = (int)DateTime.Now.DayOfWeek;
int dayOfEvent = (int)day;
if (dayOfWeek + 1 == dayOfEvent || (dayOfWeek == 6 && dayOfEvent == 0))
return "MaƱana";
switch (day)
{
default:
case DayOfWeek.Monday: return "Lunes";
case DayOfWeek.Tuesday: return "Martes";
case DayOfWeek.Wednesday: return "Miercoles";
case DayOfWeek.Thursday: return "Jueves";
case DayOfWeek.Friday: return "Viernes";
case DayOfWeek.Saturday: return "Sabado";
case DayOfWeek.Sunday: return "Domingo";
}
}
}
}
Is there some way to localize this with Cultures? how? :(
By the way I want it to say "Today" or "Tomomorrow" too, not just convert the days
DateTime.Now.ToString("ddd", new CultureInfo("es-ES"));
or
DateTime.Now.ToString("dddd", new CultureInfo("es-ES"));
References:
DateTime.ToString Method (String)
How to: Extract the Day of the Week from a Specific Date
This code from here (see bottom) might put you on the right track.
CultureInfo german = new CultureInfo("de-DE");
DateTimeFormatInfo dtfi = german.DateTimeFormat;
Console.WriteLine("Days of the week for the {0} culture:",
german.Name);
for (int ctr = 0; ctr < dtfi.DayNames.Length; ctr++)
Console.WriteLine(" {0,-12}{1}", dtfi.DayNames[ctr],
dtfi.DayNames[ctr] == dtfi.DayNames[(int)dtfi.FirstDayOfWeek] ?
"(First Day of Week)" : "");

Categories