OK, So here is my if check, no matter how I've tried it, it's not going through properly, it keeps stopping.
DateTime now = new DateTime();
string s = "Everyday";
string currentTime = now.ToString("HH:mm");
string remDate = "21:00"; //set to a minute or two i the future
string CurrentDay = "Sunday";
if ((s.ToUpper() == "WORKDAYS") ||(s.ToUpper() == "EVERYDAY" || s.ToUpper() == CurrentDay.ToUpper())
&& ((currentTime == remDate) && (s.ToUpper() != "SUNDAY") && (s.ToUpper() != "SATURDAY")))
{
MessageBox.Show("Success!!!!");
}
So when it hits the if check, it stops, never gets to the message box. No matter what order I've tried the checks it's not working, been staring at this for a while, thought someone out there could either show me a better way, or see what I'm missing.
Cause it will work only at 21:00
UPD:
Sorry, it was mistake. Real reason in first line
You have to write DateTime now = DateTime.Now;
If you see that your s is Everyday, hence the first condition is met. But you have AND condition with
(currentTime == remDate) && (s.ToUpper() != "SUNDAY") && (s.ToUpper() != "SATURDAY")
which will only be true when time is 21:00
which isn't true at this time. Hence the condition is failed.
Lets start by making your code more readable, which also helps show your || and && issues.
DateTime now = new DateTime();
string s = "Everyday";
string currentTime = now.ToString("HH:mm");
string remDate = "21:00"; //set to a minute or two i the future
string CurrentDay = "Sunday";
if (
// condition 1
(s.ToUpper() == "WORKDAYS")
// condition 2
|| (
s.ToUpper() == "EVERYDAY"
|| s.ToUpper() == CurrentDay.ToUpper()
)
// condition 3
&& (
// condition 3.1
(currentTime == remDate)
&& (s.ToUpper() != "SUNDAY")
&& (s.ToUpper() != "SATURDAY")
)
)
{
// I'm using LINQPad, so I just output this to the results
"Success!!!!".Dump();
}
One issue is condition 3.1: (currentTime == remDate). Given the sample input provided this has to be true, so your message box will only display when the time is 21:00.
Another issue is that condition 2 and condition 3 will (because they are joined with &&) be treated as a group. Is this what you really meant?
The logic of this if statement is hard to follow and the grouping or/and expressions add to the confusion.
Try writing the conditions out in english, maybe as a bullet list, and see if the mistake doesn't become obvious to you.
Here I assume that your variable CurrentDay is equal to DayOfWeek.Monday.ToString().ToUpper().
according to your statement, it looks like
if(false || true && false)
Because (s.ToUpper() == "WORKDAYS") is always false, until you change s.
and (s.ToUpper() == "EVERYDAY" || s.ToUpper() == CurrentDay.ToUpper()) is always true until you change s
and ((currentTime == remDate) && (s.ToUpper() != "SUNDAY") && (s.ToUpper() != "SATURDAY")
&& (CurrentDay == s)) is always false, because (CurrentDay == s) is false.
Hence if statement is always false, then MessageBox.Show("Success!!!!"); cannot be executed..
I got it working. I should have explained it better, what I was trying to do is have it check the time of day and then check the day, and then have an alert pop up, the values come from the end user, stored in a sqlite db.
The problem was the grouping and the order and I had a duplicate check in my code.
what i ended up with was:
if ((s.ToUpper() == "WORKDAYS") || (s.ToUpper() == "EVERYDAY" || s.ToUpper() == CurrentDay.ToUpper())
&& ((currentTime == remDate) && (s.ToUpper() != "SUNDAY") && (s.ToUpper() != "SATURDAY")))
{
}
I had it do all my OR checks first, then had it pull in the last group of AND's and then i grouped them, this works for me and does the job.
I'm writing my own reminder application and this was my weekday check that i implemented. Probably a better way to do it, but this was what i came up with.
Thanks for the help
replace:
string currentTime = now.ToString("HH:mm");
and
(currentTime == remDate)
by this:
DateTime currentTime = DateTime.Now
and
(currentTime.ToString("HH:mm") == remDate)
Related
This question already has answers here:
asp.net validation to make sure textbox has integer values
(12 answers)
Closed 4 years ago.
I've been trying to figure out how to do this for hours. How do I make the program takes only values from 1 to 6 or else it crashes?
"user only enters acceptable credit hours-- every credit hours entered is an integer between 0 and 6 and nothing else. In this case, any invalid or bad or empty input data will cause a run-time error, which is expected and is fine."
this is one of the methods i tried that did not work. I need to find out how to make the program just give a runtime error. I dont need to keep asking for input or display a message saying "error"
creditHours = double.Parse(tb_credit.Text);
if (creditHours != 1 || creditHours != 2 || creditHours != 3 ||
creditHours != 4 || creditHours != 5 || creditHours != 6)
{
creditHours = double.Parse(tb_credit.Text);
}
Mehdi is correct, however here's why your code doesn't work.
Let's say the user entered "2", then
if(creditHours != 1 || ...)
{
}
would be true because creditHours is not equal to 1, it is 2. But then let's say that the user enters "9", if(creditHours != 1 || ...) would still be true again because creditHours is not equal to 1 and is instead 9. Hence both valid and invalid values yield the same result. To correct your code you would need if(creditHours == 1 || ...).
Mehdi's code is much simpler, however I like to write;
if(0 <= creditHours && creditHours <= 6)
{
}
think it just reads better.
if (creditHours < 0 || creditHours > 6)
{
throw new Exception("Credit hours can only be between 0 and 6.");
}
Your condition is not right, because if the input number is 7 then then the condition if(creditHours != 1 || ...) will return true.
=> you should validate by this condition if (creditHours > 0 && creditHours < 6)
If user input an invalid number( ex: "abc123xyz" ) then this code will throw exception: creditHours = double.Parse(tb_credit.Text)
=> you should use TryParse to handle invalid number also.
Please check my solution as bellow:
if(!double.TryParse(tb_credit.Text, out var creditHours))
{
throw new Exception("Credit hours should be a numbers between 0 and 6.");
}
if (creditHours > 0 || creditHours < 6)
{
creditHours = double.Parse(tb_credit.Text);
}
throw new Exception("Credit hours should be a numbers between 0 and 6.")
In C#, if I want to check to make sure that a value does not equal X or Y, I would write something like this:
if(x != 1 && x != 2)
{
//dosomething
}
I want to see if there is a way to write that with OR instead of AND. Something like this (which doesn't work, but its what I am trying to do):
if(x != (1 || 2))
{
//dosomething
}
Obviously that doesn't work because it is trying to evaluate 1 || 2 as its own statement. Does there exist a way to write that correctly?
You can always invert an AND into an OR:
if (!(x == 1 || x == 2))
{
...
}
You have to reverse all the conditions to do it though, as above. The process for doing so is described in De Morgan's Laws (thanks #RichardEverett!).
You could try this one:
if(!(x == 1 || x == 2))
but honestly, I don't see the reason of doing so.
This statement if(x != 1 && x != 2) is far more clear and readable than the above and it does the same.
This (x == 1 || x == 2) evaluates to true if x is either 1 or 2. Hence taking the negation of this, you get that you want.
No, C# doesn't support such a construct presently.
The following is about as close as I could get it, but it's slow!
if (!new[] { 1, 2 }.Contains(x)) { ... }
I am currently trying to get my snake console game running but I have came up with something that I do not quite understand. I don't really think that the != operator is not working correctly, so I must have made a mistake but I have no idea why it it is like that:
// not working
if (food.x != snakeElements.Last().x && food.y != snakeElements.Last().y)
// working
if (!(food.x == snakeElements.Last().x && food.y == snakeElements.Last().y))
Isn't it all the same?
Using De Morgan's laws (!a && !b) is the same as !(a || b) so your first example should be:
if (food.x != snakeElements.Last().x || food.y != snakeElements.Last().y)
The && should be || in the first if.
if (food.x != snakeElements.Last().x || food.y != snakeElements.Last().y)
If you write out what you actually mean by your boolean condition, you can see more clearly what the difference is.
// not working
if (food.x != snakeElements.Last().x && food.y != snakeElements.Last().y)
This means:
"The food is not in the same column as the last snake element, and the food is not in the same row as the last snake element"
The logic error is a bit more obvious now. What if the food's position is (10,3), and the last element's position is (14,3)?
Compare with:
// working
if (!(food.x == snakeElements.Last().x && food.y == snakeElements.Last().y))
Which means:
"It's not true that (the food is in the same row as the last snake element and the food is in the same column as the last snake element)"
Now the condition is false if and only if the food has the same X and Y as the last snake element.
No, it is not same.
If this works...
if (!(food.x == snakeElements.Last().x && food.y == snakeElements.Last().y)) // working
Then this should work too...
if (food.x != snakeElements.Last().x || food.y != snakeElements.Last().y) // should work
Notice the change in the sign from logical AND (&&) to logical OR (||).
I think the boolean logic is different in two cases:
both comparisons must be not equal for the if to evaluate to true.
either one has to be not equal for if to evaluate to true
They are different.
To be clear, I'll call food.x as X and snakeElements.Last().x as X', others as Y and Y'.
First one is saying:
if X is different than X' AND Y is different than Y' is true
Second one is saying:
if X is equal to X' AND Y is equal to Y' is false
Assume that X, X', Y, Y' are integers
If we say that X = 3, X' = 5, Y = 1, Y' = 4, first statement is true, because X != X' Y != Y' are both true. However, second would also be true becase X is not equal to X'.
I am trying to get the total amount of time in hours between when a job is logged in a ticketing system to when then job is due. For example if the job is logged at 4:00pm on a Friday and is due at 10:30am on Monday it will have a 3 hour time span. (excluding weekends and our of business hours)
I can get the TimeSpan for total time but I have no idea how to get the TimeSpan in business hours only?
I am using LINQpad as a code scratchpad and I am querying a database.
Below is an example of the my query which gets the total TimeSpan rather than the TimeSpan in Business Hours.
(from so in TblServiceOrders
where so.DateReceived != null
&& so.TimeReceived != null
&& so.DateRequested != null
&& so.TimeRequested != null
orderby so.SONumber descending
select new
{
so.SONumber,
received = so.DateReceived.Value.AddTicks(so.TimeReceived.Value.Ticks),
requested = so.DateRequested.Value.AddTicks(so.TimeRequested.Value.Ticks),
TimeSpan = (so.DateReceived.Value.AddTicks(so.TimeReceived.Value.Ticks))
.Subtract(so.DateRequested.Value.AddTicks(so.TimeRequested.Value.Ticks))
}).Take(20)
I hope there are better ways to do this however since my TimeRange is never longer than a few days I have been able to achieve it all within the Linq Query with the below code:
This only works with LINQ-to-SQL which is unfortunate as it cannot be used in Entity Framework.
from so in TblServiceOrders
where so.DateReceived != null &&
so.TimeReceived != null &&
so.DateRequested != null &&
so.TimeRequested != null
//Get the named day of the week for start of TimeRange
let DayReceived = so.DateReceived.Value.DayOfWeek
let DayRequested = so.DateRequested.Value.DayOfWeek
//Find out how many days pass within the TimeRange
let SLADaysLapesed = ((so.DateRequested.Value.Day) - (so.DateReceived.Value.Day))
//Find out if any of those days past fall onto a Sat and therefor over a weekend.
//This will only work for the first weekend within the TimeRange.
let SLAContainsWE = (DayReceived == DayOfWeek.Monday && SLADaysLapesed <= 4 ||
DayReceived == DayOfWeek.Tuesday && SLADaysLapesed <= 3 ||
DayReceived == DayOfWeek.Wednesday && SLADaysLapesed <= 2 ||
DayReceived == DayOfWeek.Thursday && SLADaysLapesed <= 1 ||
DayReceived == DayOfWeek.Friday && SLADaysLapesed <= 0 ? false : true )
//Work out how many hours pass outside of business hours. (930 minutes)
let SLATotalDailyAH = (new TimeSpan(0, (930 * SLADaysLapesed), 0))
//Work out if the TimeRange falls over a weekend. Time declared in mins is equal to two standard working days 8.5hr x 2 in my case.
let TotalWEHours = (SLAContainsWE == true ? new TimeSpan(0,1020,0) : new TimeSpan(0,0,0))
//Work out how many Business hours have passed by removing the total after hours.
let SLAHours = (
((so.DateRequested.Value.AddHours(so.TimeRequested.Value.Hour)).AddMinutes(so.TimeRequested.Value.Minute)).Subtract
((so.DateReceived.Value.AddHours(so.TimeReceived.Value.Hour)).AddMinutes(so.TimeReceived.Value.Minute)).Subtract
(SLATotalDailyAH).Subtract(TotalWEHours)
)
select SLAHours
i am trying to check condition before entering into it but it is entering in wrong condition
my conditions are ,
if (Target.Tables[0].Rows[0]["T_B_CX"].ToString() == "0" && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) >= 100000)
if (Target.Tables[0].Rows[0]["T_B_CX"].ToString() != "0" && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) > 10000000)
the values are,
T_B_CX = 0 and T_B_C = 2500000000
it must enter the fist condition i mentioned but it is entering in second condition???
Hopes for your suggestion thanks in advance
you can convert to int and do the comparison as below
if (Convert.ToInt(Target.Tables[0].Rows[0]["T_B_CX"].ToString()) == 0 && Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]) >= 100000)
may be when we get ToString of cell value it returns not exactly string equal to "0", debug and see which value you get for Target.Tables[0].Rows[0]["T_B_CX"].ToString()
There is no code between the two conditions, so the first one is taken as expected, then the second one is evaluated till the != 0.
Try to write something like this
// Convert everything just one time here
int tbcx = Convert.ToInt32(Target.Tables[0].Rows[0]["T_B_CX"]);
long tbc = Convert.ToInt64(Target.Tables[0].Rows[0]["T_B_C"]);
if(tbcx == 0 && tbc >= 100000)
// code here
else if(tbcx != 0 && tbc > 2500000000)
// code here
Also try to avoid the conversion of an integer value to a string and then check against a string.
It makes no sense. If an integer is stored in that table then convert it to an integer and check against an integer.