I want to create a C# program that displays a calendar and uses a string that contains the names of the days:
string Names = "Sun,Mon,Tues,Wed,Thurs,Fri,Sat,";
So far I have....
int weeks = 1;
int days = 1;
string Names = "Sun,Mon,Tues,Wed,Thurs,Fri,Sat,";
string dayName;
int commaIndex = 0;
int date = 1;
while (weeks < 5)
{
while (days < 8)
{
commaIndex = Names.IndexOf(","); // find the period
dayName = Names.Remove(commaIndex);
lblCalendar.Text += dayName + "." + " " + date + " ";
Names = Names.Remove(0, commaIndex + 1);
days++;
date++;
}
weeks++;
}
But that only writes the first week.. can anybody help me figure out where there is an error?
First, you forgot to restart days variable after every iteration.
Also, after first iteration your Names string is empty.
I suggest to create array of day names and use it instead of one string.
int weeks = 1;
int days = 1;
var Names = new[] {"Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
string dayName;
int commaIndex = 0;
int date = 1;
while (weeks < 5)
{
while (days < 8)
{
dayName = Names[days-1];
lblCalendar.Text += dayName + "." + " " + date + " ";
days++;
date++;
}
days = 1;
weeks++;
}
You forgot to reset days.
while (weeks < 5)
{
days = 1
string Names = "Sun,Mon,Tues,Wed,Thurs,Fri,Sat,";
while (days < 8)
{
Related
I am new to programming I am struggling with how to end this loop.
The teacher is not helping to clarify.
The question I need to answer is "Ask the user to enter five days of the week and rainfall data for each day. Store the data in a two dimensional string array named rainfallData[]" Thanks so much!
String[,] rainFallData = new String[5, 2];
String name;
String rainFall;
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Enter the name of day " + i);
name = Console.ReadLine();
rainFallData[i - 1, 0] = name;
Console.WriteLine("Enter rainFall of day " + i);
rainFall = Console.ReadLine();
rainFallData[i - 1, 1] = rainFall;
for (int row = 0; row < 5; row++)
You can use break. When you want to end the loop just write break;.
Here is a solution that "closes the loop" by only asking for the info 5 times. It also shows how to write the data from the 2d array to the console after.
String[,] rainFallData = new String[5, 2];
for (int i = 0; i < rainFallData.GetLength(0); i++)
{
string name;
string rainFall;
Console.WriteLine("Enter the name of day " + i);
name = Console.ReadLine();
Console.WriteLine("Enter rainFall of day " + i);
rainFall = Console.ReadLine();
rainFallData[i, 0] = name;
rainFallData[i, 1] = rainFall;
}
for (int i = 0; i < rainFallData.GetLength(0); i++)
{
Console.WriteLine("Weekday: " + rainFallData[i,0]);
Console.WriteLine("Rainfall: " + rainFallData[i,1]);
}
I am trying to keep track of how many meals a person has given from two dates you can enter from DateTimePickers.
There are three meals a day between specific times between:
6-8AM Meal 1
12-2PM Meal 2
5-7PM Meal 3
If a person arrives after one of the specific times, they miss out on a meal, so for example if I arrive on 1 Jan 2018 3AM and leave on 2 Jan 2018 2PM I will only receive 5 meals, as I missed out on the last meal.
This is the code I have come up with, but unfortunately I struggle to work the code out if the time between the two dates are more than one day apart.
private void button1_Click(object sender, EventArgs e)
{
dateTimeExit.CustomFormat = "MM/dd/yyyy hh:mm:ss tt";
dateTimeArrive.CustomFormat = "MM/dd/yyyy hh:mm:ss tt";
DateTime timeArrived = dateTimeArrive.Value;
DateTime timeExit = dateTimeExit.Value;
int totalHoursArrived = timeArrived.Hour;
int totalHoursExit = timeExit.Hour;
int totalCounts = 0;
int countA = 0; //6-8 AM
int countB = 0; //12-2PM
int countC = 0; //5-7PM
int totalDaysLeft = (timeExit - timeArrived).Days; //determines the number of days between the two given dates.
if (totalDaysLeft == 1)
{
totalCounts = 3;
countA = 1;
countB = 1;
countC = 1;
}
else if (totalDaysLeft < 1) //difference between the two dates is less than a day.
{
totalCounts = totalDaysLeft * 3;
countA = totalDaysLeft;
countB = totalDaysLeft;
countC = totalDaysLeft;
if (timeExit.Day == timeArrived.Day) //if the dates are on the same day and "less than one day"
{
if (totalHoursArrived <= 8 && totalHoursExit >= 17) //if date is before or on 8AM and leaves on or after 5PM.
{
countA = 1;
countB = 1;
countC = 1;
}
else if (totalHoursArrived <= 8 && (totalHoursExit >= 12 && totalHoursExit < 17)) //if date is before or on 8AM and leaves before 5PM
{
countA = 1;
countB = 1;
}
else if (totalHoursArrived <= 8 && totalHoursExit < 12) //if date is before or on 8AM and leaves before 12PM
{
countA = 1;
}
else if ((totalHoursArrived <= 12 && totalHoursArrived > 8) && totalHoursExit >= 17) //if date is before or on 12PM and leaves on or after 5PM
{
countB = 1;
countC = 1;
}
else if ((totalHoursArrived <= 12 && totalHoursArrived > 8) && totalHoursExit < 17) //if date is before or on 12PM and leaves before 5PM
{
countB = 1;
}
else if (totalHoursArrived >= 17) //if date is after or on 5PM
{
countC = 1;
}
totalCounts = countA + countB + countC;
}
else //less than a day, but not on same day exit time.
{
if (totalHoursArrived <= 8) //if date is before or on 8AM.
{
totalCounts = 3;
countA = 1;
countB = 1;
countC = 1;
}
else if (totalHoursArrived >= 12 && totalHoursArrived < 17)// //if date is after or on 12PM and arrival time is less than 5PM
{
totalCounts = 2;
countB = 1;
countC = 1;
}
else if (totalHoursArrived >= 17) //if date is after or on 5PM
{
totalCounts = 1;
countC = 1;
}
if (totalHoursExit > 0) // exit time
{
if (totalHoursExit >= 17)
{
totalCounts += 3;
countA += 1;
countB += 1;
countC += 1;
}
else if (totalHoursExit >= 12 && totalHoursExit < 17)
{
totalCounts += 2;
countA += 1;
countB += 1;
}
else if (totalHoursExit >= 6 && totalHoursExit < 12)
{
totalCounts += 1;
countA += 1;
}
}
}
}
else //more than two days difference between the two dates.
{
**//the part I am struggling to figure out**
}
lblTotalCountA.Text = "Count A: " + countA;
lblTotalCountB.Text = "Count B: " + countB;
lblTotalCountC.Text = "Count C: " + countC;
lblTotalAmount.Text = "Total Counts: " + totalCounts;
}
I find your code quite difficult to mantain (if you would like to add a fourth meal in the future, it would be a nightmare to change your code), so I'm giving you a different approach, as well as answering your question.
First I would define a class like this:
public class DayMeals
{
private int[] entryTimes = new int[] { 6, 12, 17 };
private int[] exitTimes = new int[] { 8, 14, 19 };
private int[] mealCounts = new int[3];
private bool countHalfMeals = false;
public DayMeals(bool countHalfMeals)
{
this.countHalfMeals = countHalfMeals;
}
public void AddFullDay()
{
mealCounts[0]++;
mealCounts[1]++;
mealCounts[2]++;
}
public void CountMealsForADay(DateTime timeArrived, DateTime timeExit)
{
for (int i = 0; i < mealCounts.Length; i++)
{
int mealEntryTime = entryTimes[i];
int mealExitTime = exitTimes[i];
if (timeArrived.Hour <= mealEntryTime && timeExit.Hour >= mealExitTime)
mealCounts[i]++;
else if (countHalfMeals && timeExit.Hour > mealEntryTime && timeExit.Hour <= mealExitTime)
mealCounts[i]++;
}
}
public void PrintMealsCount()
{
for (int i = 0; i < mealCounts.Length; i++)
{
System.Console.WriteLine($"Meal #{i + 1} count = {mealCounts[i]}");
}
}
}
Then, I would simply instantiate the class and call the functions:
void Main(string[] args)
{
CalculateMeals(new DateTime(2019, 1, 1, 15, 12, 1), new DateTime(2019, 1, 2, 18, 0, 0));
}
public static void CalculateMeals(DateTime timeArrived, DateTime timeExit)
{
// Number of full days
int fullDaysNumber = (timeExit - timeArrived).Days;
DayMeals dayMeals = new DayMeals(true);
for (int i = 0; i <= fullDaysNumber; i++)
{
int hoursDiff = (int)(timeExit - timeArrived).TotalHours;
if (timeExit.Day > timeArrived.Day && hoursDiff > 24)
{
dayMeals.AddFullDay();
// A trick to make the cycle work the next time
// You can use a different variable if you want to keep timeArrived unchanged
timeArrived = timeArrived.AddDays(1);
}
else if (timeExit.Day < timeArrived.Day)
{
break;
}
else
{
if (timeArrived.Day != timeExit.Day)
{
dayMeals.CountMealsForADay(timeArrived, new DateTime(1,1,timeArrived.Day,23,59,59));
dayMeals.CountMealsForADay(new DateTime(1,1,timeExit.Day,0,0,1), timeExit);
}
else
{
dayMeals.CountMealsForADay(timeArrived, timeExit);
}
}
}
dayMeals.PrintMealsCount();
}
I tried this code and it seems to work as expected. Please review it and let me know if this is what you wanted to achieve.
NOTE: I know the usage of "AddDays(1)" is counterintuitive, because I am keeping the same hour of day 1 for a subsequent day. But, if you are not interested about the fact that a person entered at 11 on Monday rather than on Tuesday, the meals count is the same. Basically, I'm just traslating the entry time to the last day.
Here you go, without looping. I simplified further by only using standard c# objects. The trick is in counting full days and work with timespans.
public static void Main(string[] args)
{
DateTime timeArrived = new DateTime(2019, 1, 5, 13, 53, 0);
DateTime timeExit = new DateTime(2019, 1, 6, 8, 46, 0);
TimeSpan startMeal1 = new TimeSpan(6, 0, 0);
TimeSpan endMeal1 = new TimeSpan(8, 0, 0);
TimeSpan startMeal2 = new TimeSpan(12, 0, 0);
TimeSpan endMeal2 = new TimeSpan(14, 0, 0);
TimeSpan startMeal3 = new TimeSpan(17, 0, 0);
TimeSpan endMeal3 = new TimeSpan(19, 0, 0);
int daysDiff = (timeExit - timeArrived).Days;
int meals1Count = daysDiff;
int meals2Count = daysDiff;
int meals3Count = daysDiff;
TimeSpan timeDiff = timeExit - timeArrived - TimeSpan.FromDays(daysDiff);
if (timeArrived.TimeOfDay <= endMeal1 && (timeArrived.TimeOfDay + timeDiff) >= startMeal1) meals1Count++;
if (timeArrived.TimeOfDay <= endMeal2 && (timeArrived.TimeOfDay + timeDiff) >= startMeal2) meals2Count++;
if (timeArrived.TimeOfDay <= endMeal3 && (timeArrived.TimeOfDay + timeDiff) >= startMeal3) meals3Count++;
}
I havent checked this in VS but something like this should work. I copied your same day code, assuming its correct also:
public class MealCalculation
{
int countA, countB, countC = 0;
int total = 0;
public void Calculate()
{
var start = DateTime.Now;
var finish = DateTime.Now;
// Same Day
if (start.Date == finish.Date)
{
MealsCalculate(start.Hour, start.Hour);
}
// Next Day
else if (start.AddDays(1).Date == finish.Date)
{
MealsCalculate(start.Hour, 24);
MealsCalculate(0, finish.Hour);
}
// Great Than 1 Day
else
{
// First Day
MealsCalculate(start.Hour, 24);
// Middle Full Days
var days = NumberOfDays(start.Date, finish.Date);
countA += days;
countB += days;
countC += days;
// Finish Day
MealsCalculate(0, finish.Hour);
}
// Total
total = countA + countB + countC;
}
public int NumberOfDays(DateTime start, DateTime finish)
{
var days = 0;
while (start < finish)
{
start.AddDays(1);
days++;
}
return days - 1;
}
public void MealsCalculate(int totalHoursArrived, int totalHoursExit)
{
if (totalHoursArrived <= 8 && totalHoursExit >= 17) //if date is before or on 8AM and leaves on or after 5PM.
{
countA += 1;
countB += 1;
countC += 1;
}
else if (totalHoursArrived <= 8 && (totalHoursExit >= 12 && totalHoursExit < 17)) //if date is before or on 8AM and leaves before 5PM
{
countA += 1;
countB += 1;
}
else if (totalHoursArrived <= 8 && totalHoursExit < 12) //if date is before or on 8AM and leaves before 12PM
{
countA += 1;
}
else if ((totalHoursArrived <= 12 && totalHoursArrived > 8) && totalHoursExit >= 17) //if date is before or on 12PM and leaves on or after 5PM
{
countB += 1;
countC += 1;
}
else if ((totalHoursArrived <= 12 && totalHoursArrived > 8) && totalHoursExit < 17) //if date is before or on 12PM and leaves before 5PM
{
countB += 1;
}
else if (totalHoursArrived >= 17) //if date is after or on 5PM
{
countC += 1;
}
}
}
public void ImagesLinks()
{
int count = 0;
foreach(string c in DatesAndTimes)
{
if (count == 9)
{
count = 0;
}
string imageUrl = firstUrlPart + countriescodes[count] + secondUrlPart + DatesAndTimes[count] + thirdUrlPart + "true";
imagesUrls.Add(imageUrl);
count++;
}
}
The List DatesAndTimes is in this format: Each line is item in the List.
201612281150201612281150
201612281150201612281151
201612281150201612281152
201612281150201612281153
201612281150201612281154
201612281150201612281155
201612281150201612281156
201612281150201612281157
201612281150201612281158
201612281150201612281159
Europe
201612281150201612281150
201612281150201612281151
201612281150201612281152
201612281150201612281153
201612281150201612281154
201612281150201612281155
201612281150201612281156
201612281150201612281157
201612281150201612281158
201612281150201612281159
Turkey
Every 10 items there is a name.
I want to skip the name when i build the links.
So i count to 9 each time ( count 10 times from 0 to 9 ) then i reset the counter to 0 and i also want to skip the name for example Europe then count to 10 again and skip Turkey and so on.
You can also use (count % 9 == 0), this way you don't have to reset the counter:
public void ImagesLinks()
{
int count = 0;
foreach(string c in DatesAndTimes)
{
if (count++ % 9 == 0)
continue;
string imageUrl = firstUrlPart + countriescodes[count] + secondUrlPart + DatesAndTimes[count] + thirdUrlPart + "true";
imagesUrls.Add(imageUrl);
}
}
Use continue in the if statement. It will skip the line after and resume the foreach loop execution.
public void ImagesLinks()
{
int count = 0;
foreach(string c in DatesAndTimes)
{
if (count == 9)
{
count = 0;
continue;
}
string imageUrl = firstUrlPart + countriescodes[count] + secondUrlPart + DatesAndTimes[count] + thirdUrlPart + "true";
imagesUrls.Add(imageUrl);
count++;
}
}
I have a multidimensional array that represents the days of the week (Monday, Tuesday etc..) and weeks for a month (Week 1 etc..), which shows the amount of products made on each day. The array is being filled by user entry (Input box) and I am trying to figure out a way to prompt the user for a week: Week 1 etc and a day. I know of IndexOf but that gives me the index not the value in the index.
My code is:
int[,] week = new int[4, 5];
for (int Row = 0; Row < week.GetLength(0); Row++)
{
if (Row == 0)
{
Week = "Week 1 ";
}
else if (Row == 1)
{
Week = "Week 2 ";
}
else if (Row == 2)
{
Week = "Week 3 ";
}
else if (Row == 3)
{
Week = "Week 4 ";
}
txtOutput.Text += "\r\n" + Week + ": ";
for (int Col = 0; Col < week.GetLength(1); Col++)
{
if (Col == 0)
{
Day = "Monday";
}
else if (Col == 1)
{
Day = "Tuesday";
}
else if (Col == 2)
{
Day = "Wednesday";
}
else if (Col == 3)
{
Day = "Thursday";
}
else if (Col == 4)
{
Day = "Friday";
}
string value = Microsoft.VisualBasic.Interaction.InputBox("Enter the amount of products made on " + Day + " for " + Week, "Product Amount");
week[Row, Col] = Int32.Parse(value);
txtOutput.Text += " ";
txtOutput.Text += value + " ";
}
}
I will probably have to make some custom method for this as there is no inbuilt method I know of but I cannot figure out what this would look like. Any help would be appreciated.
week[Row, Col] is just the answer.
e.g. week[0,3], week[2,4]...
I am working on c# application and i want to accomplish following task:
I have 12 check boxes for 12 items and user can check any of the check boxes.
if check boxes 3,4,5,6,8,10,11,12 have been checked, I would like to display following output.
You have selected items 3-6,8,10-12.
Rules:
When consecutive number group count is 3 or more than 3,Show grouping like 3-6
else show individual number. 8
Firstly I suggest you to append value of all the checkbox in string like you have shown.
Function Calling :
string data = "3,5,6,7,8,10,12";
string res = GetResultString(data);
Functions :
string GetResultString(string data)
{
string[] arrData = data.Split(',').ToArray();
List<int> lstData = new List<int>();
foreach (string item in arrData)
{
lstData.Add(Convert.ToInt16(item));
}
lstData.Sort();
string finalStr = string.Empty;
if (lstData.Count > 0)
{
int start = lstData[0];
int end = start;
finalStr = string.Empty;
for (int index = 1; index < lstData.Count; index++)
{
if (end + 1 == lstData[index])
{
end = lstData[index];
}
else
{
finalStr += appendResult(start, end);
start = -1;
}
if (start == -1)
{
start = lstData[index];
end = lstData[index];
}
}
finalStr += appendResult(start, end);
}
finalStr = finalStr.Trim(',');
return finalStr;
}
string appendResult(int start,int end)
{
string res = string.Empty;
if (end - start > 1)
{
res += start + "-" + end.ToString() + ",";
start = -1;
}
else
{
while (start <= end)
{
res += start.ToString() + ",";
start++;
}
}
return res;
}
Hope this will done your job,
try this .. it will work i tested it
I have not created checkboxes so it is up to you to check which checkbox is selected get the string like from the selected checkboxes 3,4,5,6,8,10,11,12
string str1 = "3,4,5,6,8,10,11,12";
string[] strArr = str1.Split(',');
List<string> strFinal = new List<string>();
int[] myInts = Array.ConvertAll(strArr, s => int.Parse(s));
int arrLn = myInts.Length;
Array.Sort(myInts);
int intPrevVal = myInts[0];
int intPrevDiff = myInts[0];
int seriesCount = 1;
strFinal.Add(Convert.ToString(myInts[0]));
for (int j = 1; j < arrLn; j++)
{
int intCurr = myInts[j];
if (intCurr - intPrevVal == 1)
{
seriesCount++;
}
else
{
if (seriesCount >= 3)
{
strFinal[strFinal.Count - 1] = strFinal[strFinal.Count - 1] + "-" + intPrevVal;
seriesCount = 1;
}
else if (seriesCount == 2)
{
strFinal.Add(Convert.ToString(myInts[j - 1]));
seriesCount = 1;
//strFinal.Add(Convert.ToString(myInts[j]));
}
strFinal.Add(Convert.ToString(myInts[j]));
}
intPrevVal = intCurr;
}
if (seriesCount >= 3)
{
strFinal[strFinal.Count - 1] = strFinal[strFinal.Count - 1] + "-" + myInts[arrLn - 1];
}
else if (seriesCount == 2)
{
strFinal.Add(Convert.ToString(myInts[arrLn - 1]));
}
string FinalAns = string.Join(",", strFinal.ToArray());
Response.Write(FinalAns);
I suppose you did your checkbox with array (new...) if not do it maunally...
int min=13;
int max=0;
string s = "";
for (int i = 0; i<12; i++)
{
if (cb[i].checked && i<min)
min = i;
else if (cb[i].checked == false)
if (min != 13)
{
max = i-1;
s = s + min.ToString() + "-" + max.ToString() + " ";
min = 13;
}
}
if (cb[11].checked) s = s + min.ToString() + "-12"; // for case the last one is checked
// s contains your data
(I didn't check it but I think it need to be something like this.)
try this
var data = new List<int> { 3, 4, 5, 6, 8, 10, 11, 12 };
// data.Sort();
var groups = new List<string>();
var startIndex = 0;
for (var i = 1; i < data.Count; i++)
{
if (data[i - 1] == data[i] - 1)
{
continue;
}
groups.Add(startIndex == i - 1
? data[startIndex].ToString()
: data[startIndex] + "-" + data[i - 1] );
startIndex = i;
}
groups.Add(startIndex == data.Count - 1
? data[startIndex].ToString()
: data[startIndex] + "-" + data[data.Count - 1]);
var result = string.Join(",", groups);
version 2
[Fact]
public void Test()
{
var data = new List<int> { 3, 4, 5, 7, 8, 10, 11, 12 };
// data.Sort();
var groups = new List<string>();
var startIndex = 0;
for (var i = 1; i < data.Count; i++)
{
if (data[i - 1] == data[i] - 1)
{
continue;
}
AddToGroups(groups, startIndex, i, data);
startIndex = i;
}
AddToGroups(groups, startIndex, data.Count, data);
var result = string.Join(",", groups);
Assert.Equal("3-5,7,8,10-12", result);
}
private static void AddToGroups(List<string> groups, int startIndex, int actualIndex, List<int> data)
{
switch (actualIndex - startIndex)
{
case 1:
groups.Add(data[startIndex].ToString());
break;
case 2:
groups.Add(data[startIndex].ToString());
groups.Add(data[startIndex + 1].ToString());
break;
default:
groups.Add(data[startIndex] + "-" + data[actualIndex - 1]);
break;
}
}
You might have got the solution,but all the above solutions use string for appending data..You could use StringBuilder for optimized performance.
List<int> selectedCB = new List<int>() { 3, 4, 6, 7, 8, 9, 11, 12 };
string output = GetFormattedOutput(selectedCB);
The code for formatting data..
private string GetFormattedOutput(List<int> selectedCB)
{
// Can be changed if you want to increase
// groupby range
int rangeBy = 3;
int diffBy = 1;
int prevValue = 0;
List<int> tempList = new List<int>();
StringBuilder formattedOutput = new StringBuilder();
foreach (int currentValue in selectedCB)
{
var diff = currentValue - prevValue;
if(tempList.Count != 0 && diff > diffBy)
{
// Add the value in templist to formatted output
// If three are more numbers are in range
// Add the first and last
if (tempList.Count >= rangeBy)
{
formattedOutput.Append(tempList[0].ToString() + "-" +
tempList[tempList.Count - 1].ToString()+",");
}
else
{
AppendText(formattedOutput, tempList);
}
tempList.Clear();
}
tempList.Add(currentValue);
prevValue = currentValue;
}
if (tempList.Count != 0)
{
AppendText(formattedOutput, tempList);
}
formattedOutput.Remove(formattedOutput.Length - 1, 1);
return formattedOutput.ToString();
}
// To append the numbers in the list
string AppendText(StringBuilder output, List<int> tempList)
{
foreach (var temp in tempList)
{
output.Append(temp.ToString() + ",");
}
return output.ToString();
}