Complex if-statement in an textchanged event - c#

I want to realize a complex if-statement. The if-statement is in an textchanged event of a textbox. If the if-statement gives true, a pdf-file should be load. The problem is not how to load the PDF-file, thats works already fine, the problem is, how set the if-statement. There, the following conditions should be queried:
At position 0 must be an "S",
at position 1 must be an "E",
at position 2 must be an "H",
position 3 does not matter,
position 4-7 represent a number and the number must be from 0-3000 (not allowed to go over 3000),
at position 8 must be again an "H" or an "R"
I tried it with the method IndexOf() and it works for the first 3 characters, but in connection with the 8th sign it did not work anymore. I think it is related to the fact that "H" already exists at position 2.
To check the number I tried it with:
Convert.ToInt32(textBox1.Text.Substring(4, 4)) <= 3000
But that did not work either.

private static bool ShowPdf(string str)
{
if (str[0] != 'S')
return false;
else if (str[1] != 'E')
return false;
else if (str[2] != 'H')
return false;
else if (str[8] != 'H' && str[8] != 'R')
return false;
else if (int.TryParse(str.Substring(4,4), out int number)
return (number >= 0 && number <= 3000);
return true;
}

Related

How to update variable from with if statement MQL5

I have been googling for two days now, but can't figure this out and it seems to be basic.
Within the void OnTick(), I would like to create a variable int a;. Lets say it starts out with no value int a;, then I test condition if a is NULL or || equals 1 like this if (a == NULL || a == 1) which should always return true the first time the if statement runs due to NULL. I then assign a value to the variable a = 0;, so now a should equal 0.
This should trigger the else if(a == 0) the next time OnTick() is called, at this point I assign a = 1; resulting in the if being triggered next time round, etc and infinitum, constantly checking and assigning values switching between 0 and 1.
void OnTick()
int a;
if (PositionsTotal() < 1)
{
if(a == NULL || a == 1)
{
a = 0;
}
else if(a == 0)
{
a = 1;
}
}
I do not know what is going on, but during Testing in Strategy tester, I am getting a long string of numbers which switches between negatives and positives always with the same number -123456789 or 123456789, always 9 digits long.
Or during Debugging from Meta Editor. A random positive 3 digit number which never changes!
So far I have had both 303 and 597.
Beyond frustrating and most likely answered somewhere else.
Just not sure how to phrase the search term.
Thanks for you help.
I think the problem is that you declare your variable a inside the method OnTick, so it starts with an arbitrary value every time you call this method. Try declaring it outside this method.

c# recursion check if even

I need help understanding this. I really don't understand this piece of code and could someone here explain exactly what happens?
So this is the code:
static bool IsEven(int n)
{
if (n == 0) return true;
if (IsEven(n - 1))
{
return false;
}
else
{
return true;
}
}
And then I do this:
Console.WriteLine(IsEven(10));
How does it actually work? If I enter in number 10, it prints out true. If I enter number 7, it prints out false. But I don't understand why it even works.
It checks if the number is 0, then it returns true. But I entered 10 (which clearly is not 0) and it still print out true. Then it checks number -1.
So that would be 10-1, which is 9. But how does it know that 9 is NOT even? (it returns false).
I don't understand this code, but it works. I am so confused honestly.
Walk through it logically using a lower number like 3 so there are not as many recursions to think about.
The first time we call IsEven(3); it does this:
if (3 == 0) return true;
Well 3 does not equal 0 so it continues with this:
if (IsEven(3 - 1))
Which is the same as:
if (IsEven(2))
So now we're in the next call to IsEven. The first check is 2 == 0 which of course it is not, so it continues with IsEven(2 - 1).
Now we're in the third call to IsEven with IsEven(1). Well again 1 == 0 is not true so it continues with IsEven(1 - 1).
Now we're in the final (fourth) call to IsEven with IsEven(0). Well now 0 == 0 is true so we return true back to the third call.
So now back in the third call IsEven(1 - 1) is true so it performs the action in the first bracket which is to return false.
Back in the second call IsEven(2 - 1) is now false so it takes the action in the second bracket which is return true.
Back in the first call IsEven(3 - 1) is true so it takes the action in the first bracket which is to return false indicatining that 3 is indeed not even.
It's like integer inception.
Of course a real example would probably use the modulo % operator like this.
public static bool IsEven(int number)
{
return number % 2 == 0;
}
Think of it like this:
IsEven(3)
| IsEven(2)
| | IsEven(1)
| | | IsEven(0)
| | | Return True
| | Return False
| Return True
Return False
It's always going to eventually get to 0 if the input was non-negative and start going back up the chain. IsEven(1) above means that IsEven(2) and IsEven(3) is still being executed. Those method calls have not ended yet.
What the IsEven(n) method is doing is returning the opposite of the lower number. Passing in 4 means it has to check if 3 is even. Since it isn't, it will return true for 4.
As others have mentioned, I would suggest writing it out, but I would also suggest a breakpoint and using the Step-In IDE command to go into the IsEven method so you can watch the parameter value change and follow the flow as it is happening. Or at least add in some Console.WriteLine for you watch.
Let's try to understand it starting with mathematics. 0 is even by a definition. We know that each addition of 1 will flip the "eveness" of the number. So we can write the reursive rule as follows:
Base case: IsEven(0) = true
Induction: IsEven(n) = NOT( IsEven(n-1) ) ; for n > 0
So we can easily code it:
static bool IsEven(int n)
{
if (n == 0) return true;
return (!IsEven(n - 1));
}
So far so good. But note, the (!A) can be rewritten instead as this awkward condition:
if (A)
{
return false;
}
else
{
return true;
}
You can convince yourself by substituting A with true or false.
Now we just substitute A with IsEven(n-1) and paste it to the above code and get the original
static bool IsEven(int n)
{
if (n == 0) return true;
if (IsEven(n - 1))
{
return false;
}
else
{
return true;
}
}

Only one "0" before "." in textBox_TextChanged

How can I left only one "0" before "."? I'm making TextBox which accepts only digits and you can write only one "0" before ".", but you can write any numbers like 900 or 5000.
Here is the pseudocode I use:
if (0 > 1 before "." && 0 is first digit)
{
Remove all zeros before "." and left one;
}
Simplest way is probably to remove ALL of the 0 at the start;
textbox.Text = textbox.Text.TrimStart('0');
And then if it starts with '.' add a '0' back on the beginning again.
if (textbox.Text.StartsWith('.'))
textbox.Text = '0' + textbox.Text;
This will also remove any 0 at the beginning of, for example, "00500", changing it to "500", which is probably a good thing.
use it like this
for (int i=0;i<textbox.Text.Length;i++)
{
textbox.Text=textbox.Text.Replace("00.","0.")
}
Relaying on TextChanged event have some drawbacks. For example user may want to enter zeroes and then precede them by digit (.) symbol. Your code would delete all leading zeroes before digit is entered. It is better to use other event like Validating or LostFocus. Code would be quite simple:
textbox.Text = textbox.Text.TrimStart('0');
You may use NumericUpDown control for numeric-only input. It will validate whether text is a number and format it according to settings like DecimalPlaces.
Maybe this one can help:
public string ZeroPoint(string a)
{
int pos = a.IndexOf(".");
if (pos > -1 && a.Substring(0, pos) == new string('0', pos))
{
a = "0" + a.Substring(pos, a.Length - pos);
}
return a;
}
You need to use the KeyPress event and add the below logic to determine what is being pressed and where the entered value is going to be placed.
When you set the e.Handled value to true then you are telling the system to ignore the users input.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// Only allow digits, decimal points and control characters (Backspace, delete, etc)
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
{
e.Handled = true;
}
int PointIndex = (sender as TextBox).Text.IndexOf('.');
// only allow one decimal point and one digit before decimal point
if (((e.KeyChar == '.') && PointIndex > -1) ||
(e.KeyChar == '.' && textBox1.SelectionStart > 1) ||
(PointIndex == 1 && textBox1.SelectionStart <= PointIndex))
{
e.Handled = true;
}
}
This code validates the users input as they are typing.
EDIT:
Also since this code only validates the input as the user is typing you will also want to prevent them pasting in invalid values. You can do this by setting the ShortcutsEnabled property of the textbox to false.

While loop not properly checking all conditions?

So the assignment is as follows: you can enter all sorts of numbers but when you enter 0 two times in a row it needs to stop. The first time you enter a number your not allowed to enter 0.
This is the code I have setup:
class MainClass
{
public static void Main (string[] args)
{
int givenNumber, prevNumber;
Console.WriteLine ("Enter a number: ");
int.TryParse (Console.ReadLine (), out givenNumber);
// I've set the prevNumber to givenNumber because the variable has to be initialized
// before I can use it in the condition below. I thought setting it to the giveNumber
// wouldn't harm. Note that the first time your not allowed to enter 0
prevNumber = givenNumber;
while (givenNumber != 0 && prevNumber != 0) {
prevNumber = givenNumber; //Here is where they both are 0 at a given moment, but only after the condition.
Console.WriteLine ("Enter a number: ");
int.TryParse (Console.ReadLine (), out givenNumber);
}
Console.WriteLine ("Tada");
}
}
The problem is that it already stops when you've only entered one 0. For example if I'd first enter a 7 to start with, and my next number would be 0. When I debug it it says that my givenNumber is 0 and prevNumber is 7, when it goes back to the while condition it stops and finishes. When the program finishes the debug clearly says prevNumber = 7 and givenNumber = 0. I am using the conditional AND correct am I not?
Any clue? I'm not allowed to use arrays for this matter.
Thanks in advance
Ooh, right, you've got the logic wrong. It should be this:
while ((givenNumber != 0) || (prevNumber != 0)) {
Look up DeMorgan's laws to see why...
Your problem is with your conditional statement.
Right now you're checking whether both the givenNumber and the PrevNumber DO NOT equal 0.
So, if neither of them equals 0 then the statement will evaluate to TRUE. However, if either one of the numbers is 0 then the statement will evaluate to FALSE, since (TRUE) && (FALSE) evaluates to FALSE.
There are two ways to fix this: You can either use || (the "OR" operator) with the two "!=" statements, or you can negate the whole thing and use regular equality rather than "!=" as such: !(givenNumber == 0 && prevNumber == 0)
while (givenNumber != 0 && prevNumber != 0)
For first read value from console - number 7
givenNumer will be 7
prevNumber will be 7 too (because of assignment prevNumber = givenNumber;)
Thus while (7 != 0 && 7 != 0) will pass
Second read from Console - number 0
Thus while (0 != 0 && 7 != 0) will not pass because 0 != 0 is FALSE and while loop ends if condition is result is FALSE

Why does while loop OR not work but AND does?

I have a simple while loop in C# and basically I'm testing two conditions
while (opponentOne.HP >= 0 || opponentTwo.HP >= 0)
Which when I read this means, while the first opponents HP is more than equal to 0 OR the seconds opponents HP is more than equal to 0, exit. So when only one of them are true, exit the while loop?
However this does not do what I want it to do, it waits for both of them to become true before exiting the loop, however if I change || to && it will work
while (opponentOne.HP >= 0 && opponentTwo.HP >= 0)
Which now says while the firsts opponents HP is more than 0 and the seconds opponent is more than 0, exit...
Have I got something mixed up here?
I thought the loop should break when both conditions are met.
The condition isn't the condition "to exit", it's the condition to continue
So first one says "continue looping as long as either oponents have >0HP" and the second one says "continue as long as both opponents have >0HP"
A while loop will keep looping until the condition BECOMES FALSE.
So in the first case :
NOT (1.HP >= 0 || 2.HP >= 0)
if we apply DeMorgan's equivalency to it:
It will break when
NOT 1.HP >= 0 AND NOT 2.HP >= 0
Have I got something mixed up here?
Yes, && means that both sides must be true(both oppponents must be alive), otherwise the loop is exited.
|| means that one of both sides must be true, so only one opponent must be alive.
Replace the while-loop with an if-statement(for demonstration purposes only):
if(opponentOne.lives && opponentTwo.lives)
{
// do something
}
else // one is dead
{
// exit
}

Categories