naming days of the week, how to iterate through strings?
Hey im new in C# i asume its easy but anw im trying to build simple clock as stydying program for myself So far ive made seconds:minutes:hours:days: and so on each loop trigers another with if statements its all works perfect untill i got to naming months and days of the week. I have no clue how to loop thru strings and how trigger the change in already existing system. tnx in advance :) example of the existing loop:
if (second >= 60)
{
minute ++;
second = 0;
TextCallFunction ();
} else if (minute >= 60)
{
hour ++;
minute = 0;
TextCallFunction ();
} else if (hour >= 24)
{
day ++;
hour = 0;
ChangeDay ();
TextCallFunction ();
} else if (day >= 28)
{
TextCallFunction ();
} else if (month >= 12)
{
year ++;
month = 1;
TextCallFunction ();
}
Answer by Harinezumi · Jan 29, 2018 at 09:16 AM
Unless you are doing this as an exercise (which you said you are), in C# use System.DateTime which handles all the nuances of dates and times (although the API is a bit clumsy).
To cycle through strings you usually have an array (or even better, List) of your strings and store an index into it, but display your value. For example:
private string[] namesOfMonths = { "January", "February", "March", "etc.", "I'm too lazy to type it all out" };
private int monthIndex = 0; // you increase this value at the end of month; watch out, January is the 0th month in the array!
void TextCallFunction () {
// ...
string nameOfMonth = namesOfMonths[monthIndex]; // make sure monthIndex never reaches 12!
// display the name of the month
// ...
}
Btw, watch out that not all months are the same length, and some years are leap years... you have to handle all of these if you want a perfectly working clock.
Answer by frapes123 · Jan 29, 2018 at 01:15 PM
Thanks alot man! works like a charm. Didnt think about adding another int to do the counting.
private string[] dayType = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
private int dayTypeIndex = 0;
private string dayTypeS;
void ChangeDay ()
{
dayTypeS = dayType[dayTypeIndex];
if (dayTypeIndex >= 7)
{
dayTypeIndex = 0;
}
}
im not sure that "if" statement gonna work tho...
Change the order of your if condition and assigning the dayTypeS, because this way dayTypeIndex can reach 7, but you can only validly index your array until 6!
Another way is to use the modulo operation like this: dayTypeIndex = (dayTypeIndex + 1) % 7; // or you can even use dayType.Length ins$$anonymous$$d of 7!
And you're welcome! (you can accept an answer if it solved your problem ;) )
Your answer