Simple and fine for loop doesn't work - c#

I feel stupid to ask this question but i got headache trying to find out why this simple for loop didn't work.
private void button2_Click(object sender, EventArgs e)
{
for (int i = 1; i>=5; i++)
label2.Text = "aaaa";
}

you're using a greater than sign, use the less than
private void button2_Click(object sender, EventArgs e)
{
for (int i = 1; i<=5; i++)
label2.Text = "aaaa";
}

first iteration: 1==5 which evaluates to false, so it will exit
You should read how the for loop works.
Statement 1 is executed before the loop (the code block) starts. Statement 2 defines the condition for running the loop (the code block), if it is true Statement 3 is executed after the loop (the code block) has been executed.
And this repeats until statement 2 becomes false

Related

Comparing string from label and input(textBox) and showing result in label. Plus operation on array

I'm writing a FlashCard app in Windows Form.
Right now I'm trying to do is read word from string array and pass it to label. Then asking user to write the translation of this word. And finally pass the result to label box.
Here is my code:
public partial class EnglishPolishScreen : Form
{
//English words array
string[] words = new string[] { "word1", "word2", "word3", "word4" };
// meanings words array
string[] wordB = new string[] { "slowo1", "slowo2", "slowo3", "slowo4" };
int element = 0;
Thread thread;
public EnglishPolishScreen()
{
InitializeComponent();
}
private void CloseAppEvent(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
thread = new Thread(Threadd);
thread.Start();
}
private void Threadd()
{
englishWord.Text = words[element];
counterLabel.Text = element + 1 + " of " + words.Length;
if (answerBox.Text.Equals(wordB[element]))
{
resultLabel.Text = "Good";
element++;
}
else
resultLabel.Text = "Bad";
if (element == words.Length)
{
element = 0;
}
}
private void EnglishPolishScreen_Load(object sender, EventArgs e)
{
englishWord.Text = words[element];
}
Edited
Guys, Why I have to click two times in button to see next item from array? And why I can see "bad" answer straight after I click button? The "Good" answer shows up after second click.
Edited v2.xD
Sorted. Anyway is it good way to write code like this? If not how It could look better? Thanks
Regards
On button click, it is going through the whole for loop, i.e. the entire list of meanings, you would have to break the for loop as soon as a right match is found. So just use break; after resoultLabel.Text = "Good answer!";. Also as pointed out by #Neil, it is not good to use UI in a separate background thread.
By the way, I am not able to wrap my head around the logic of chances. For giving chances you would have to declare a global variable which would get added/subtracted when the a bad answer is found after Iterating through whole for loop, disallowing any further trial for the word.

Pin code application that increments number of attempts

I have been trying to finish this small application for counting the number of attempts if you fail to write the correct pin code.
This is my code so far, and I am not understanding why my code isn't working and it keeps on incrementing non stop.
private void btn_login_Click(object sender, EventArgs e)
{
int attempts = 0;
int pin_number;
do
{
pin_number = int.Parse(txt_pin.Text);
MessageBox.Show("Hi There");
if (pin_number != 1326)
{
attempts++;
MessageBox.Show($"pin code is incorrect you have {attempts} of 3 attempts left");
txt_pin.Text = "";
txt_pin.Focus();
}
} while (pin_number == 1326 && attempts < 3);
}
Every time you click the button is an "attempt", correct? Well, what's the first thing you do every time you click the button...
int attempts = 0;
So every attempt is the first attempt. Except when the user gets it right. Then what you have is an infinite loop because the pin_number is correct and attempts is never incremented.
First, get rid of the loop entirely. There's no need to repeatedly check the same input. Once it's checked, it's checked. Second, track the number of attempts outside the scope of each attempt, such as at the class level. Third, check the number of attempts. Perhaps something like this:
private int attempts = 0;
private void btn_login_Click(object sender, EventArgs e)
{
int pin_number;
pin_number = int.Parse(txt_pin.Text);
MessageBox.Show("Hi There");
if (attempts < 3 && pin_number != 1326)
{
attempts++;
MessageBox.Show($"pin code is incorrect you have {attempts} of 3 attempts left");
txt_pin.Text = "";
txt_pin.Focus();
}
}
Now it's at least checking the pin as expected. Though at this point you have some logic to reconsider for your program. Off the top of my head...
It never notifies the user if they got the pin right. Perhaps something else should happen?
After the number of attempts is exhausted, there's no warning to indicate this. It looks exactly as it does if the pin is correct.
The text implies that the number of attempts is counting down, but it's actually counting up.
Perhaps something like this might get you started:
private int attempts = 3;
private void btn_login_Click(object sender, EventArgs e)
{
int pin_number;
pin_number = int.Parse(txt_pin.Text);
MessageBox.Show("Hi There");
if (attempts <= 0)
{
MessageBox.Show($"No more attempts left");
}
else if (pin_number != 1326)
{
attempts--;
MessageBox.Show($"Pin code is incorrect you have {attempts} attempts left");
txt_pin.Text = "";
txt_pin.Focus();
}
}
Examine each statement in the logic. For your own logic, particularly around if blocks and loops and whatnot, perhaps even grab a piece of paper and draw out the different code paths and write down in each path what should happen there. Every detail is important, such as when to show a message or when to modify a value. There's a lot of polish that can be added to this code, and I imagine it's an academic exercise so I'll leave that to you.
Right now you have a loop inside your button click handler. You probably don't want that since you want to enable the user to enter a new pin code and click the Login button again.
But that also means that you need to store the number of attempts outside the click handler, since it needs to be saved from one click to the next.
So if you change your code to something like this, I think you'll get the functionality you're after
private int attempts = 0;
private void btn_login_Click(object sender, EventArgs e)
{
int pin_number;
pin_number = int.Parse(txt_pin.Text);
MessageBox.Show("Hi There");
if (pin_number != 1326)
{
attempts++;
MessageBox.Show($"pin code is incorrect you have {3-attempts} of 3 attempts left");
txt_pin.Text = "";
txt_pin.Focus();
}
if (attempts >= 3)
{
btn_login.Enabled = false;
}
}

timer stopped and jump to certain second

I made a sample project. Where every 10 second it do some function. But when I try to show a timer tick in label it always stuck, and jump to certain second (eg: stuck at 9s and suddenly jump to 12s). What i want to ask,
Is my function run properly ?
Is my tick, skipped a few ms ? (it will overlap with my function)
How do I run it as a thread ?
My code
private void button2_Click(object sender, EventArgs e)
{
timer1.Start();
}
int x = 0;
private void timer1_Tick(object sender, EventArgs e)
{
x += 1;
label1.Text = x.ToString();
if (x % 10 == 0)
{
addpoint();
//MessageBox.Show("success");
}
}
how to keep my label1.text keep updating, while do addpoint() function
Note:
I have set timer1 interval = 1000
update
i test it with this.
public void addpoint()
{
string x = #"c:\test\a.txt";
string text = "haiaiaia";
using (FileStream fs = new FileStream(x, FileMode.Create))
{
Byte[] xx = Encoding.ASCII.GetBytes(text);
fs.Write(xx, 0, xx.Length);
}
Messagebox.show("Created !");
}
It looks like your using a Windows.Forms.Timer which is executed on the main thread. The advantage is that you don't need to call Invoke, the disadvantage is that addpoint is also executed on the main thread and hence blocks your GUI from update, when in the mean time the next tick events are fired.
You can verify it be replacing the call of addpoint with Thread.Sleep(3000) and you will experience the same behaviour.
What you could do is to try and run the method on another thread:
private void timer1_Tick(object sender, EventArgs e)
{
x += 1;
label1.Text = x.ToString();
if (x % 10 == 0)
{
Thread t = new Thread(addpoint);
t.Start();
}
}
This should avoid the blocking of the GUI.
Disclaimer:
It is important to know what you actually do in addpoint, because this solution might lead to race condition and wrong functioning of the method. For example if you are using class variables in it, and if the possibility exists that a second thread can be started while the first has not finished yet! Be aware.

autoscroll a textbox in c# 1 line down every x seconds

im trying to get a textbox to autoscroll a line down every X seconds.
i have found the AutoScrollOffset and ScrollToCaret functions, but these functions do not give the desired result.
I think my solution would be to do the autoscroll function in a backgroundworkerthread, that does a scroll down by 1 line every x seconds. But i have no idea how to, and info from the net isnt verry usefull either.
I hope someone can help me, thnx in advance!
(im using .net 4.5)
Borrowing heavily from this answer, and combining it with a Timer, you could do something like this:
private int lineNumber = 1;
private void timer1_Tick(object sender, EventArgs e)
{
nfobox.HideSelection = false;
nfobox.SelectionStart = nfobox.GetFirstCharIndexFromLine(lineNumber - 1);
nfobox.SelectionLength = nfobox.Lines[lineNumber - 1].Length;
nfobox.ScrollToCaret();
lineNumber++;
// include some code to detect the last line, or you'll get an exception
}
This will only work if your lines are separated by a line feed.
If it's one long line that wraps, then the whole thing will be selected on the first "tick" and then it's done.
"Grant Winney" is rigth. you can't directly modify the Uİ from a background thread.
But You use the way below.
int lineCounter = 0;
int nextLineLength = 0;
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.SelectionStart = nextLineLength;
textBox1.SelectionLength = 0;
textBox1.ScrollToCaret();
nextLineLength += textBox1.Lines[lineCounter++].Length + "\r\n".Length; //"\r\n" is next line parameters
}

Do loops and while loops

When I type in the word "Andrea" the program crashes. I am guessing, but I think it's because I am inside the loop and it doesn't know when to stop. If I am correct can you tell me how to get out of the loop. when I put a break in it tells me there is no loop to end.
private void button1_Click(object sender, EventArgs e)
{
do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
while (textBox1.Text == "Andrea");
break;
do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
while (textBox1.Text == "Brittany");
do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
while (textBox1.Text == "Eric");
break;
MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
You have textBox1.Text == "Andrea" and textBox1.Text == "Brittany" as your loop conditions, but you don't seem to be changing that value anywhere in the code. Therefore, you have an infinite loop which will result in your program crashing.
I'm not certain what your program is meant to be doing, but your options to break out of a loop are:
Use a break; statement to exit the loop.
Change your loop condition to something which can eventually result in false.
Change the textBox.Text property somewhere in the loop body.
Alternatively, you could use an if statement to check the condition once, and execute some code if that condition is true.
Edit:
I have done this with if statements but now i am looking to try doing the same thing with loops
no purpose just trying to learn how to program
In response to the above comments, I'll tell you how to replace an if statement with a loop. Just do it like so:
// Check the condition before executing the code.
while (textBox1.Text == "Andrea") {
// Execute the conditional code.
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
// We actually only want to execute this code once like an if statement,
// not while the condition is true, so break out of the loop.
break;
}
In your original post, you are using a do while loop rather than a while loop. You should keep in mind that the do while executes once for certain, regardless of whether its condition is true. It only checks the condition to see whether it should run additional times. The while loop, on the other hand, checks the condition before executing at all, which means you can substitute an if statement with it.
You should keep in mind that this is a bad practice. If you want to execute code depending on a certain condition, use an if statement. If you want to execute code repeatedly a certain number of times or while some condition is true, then use a loop.
At a glance, it looks like you have an infinite loop. As soon as you type in "Andrea" in textBox1 and click button1, it will perpetually update Commission.Text, not interrupting the thread to process any additional input.
The bigger question is, what the heck is this program supposed to be doing? And why is it doing it in a loop?
I suspect that by while you actually mean if. Otherwise, do you get an error message or exception when the application crashes? Can you wrap this function in a try/catch to see what the exception is?
Edit To clarify, try this method body:
private void button1_Click(object sender, EventArgs e)
{
try
{
if(textBox1.Text == "Andrea")
{
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
}
else if(textBox1.Text == "Brittany")
{
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
}
else
{
MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "Bad Spelling");
}
}
}
}
Adding to what FacticiusVir said earlier, you can also do this in a switch statement (and since we're calculating the same commissions for each person, they can be combined:
private void button1_Click(object sender, EventArgs e)
{
switch(textBox1.Text)
{
case "Andrea":
case "Brittany":
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
break;
default:
MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
}
}
If you want to do different commissions per person you need to split it (in the below Brittany is getting a different commission value now):
private void button1_Click(object sender, EventArgs e)
{
switch(textBox1.Text)
{
case "Andrea":
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
break;
case "Brittany":
Commission.Text = (Convert.ToDouble(textBox2.Text) / 15).ToString();
break;
default:
MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
}
}
The do { x } while (y) construct runs x once, and then proceeds to run x continuously as long as y is true.
You're not having any success because you seem to be structuring it like this:
do
{
// This will just run over and over...
}
while (condition); // ...because this is always true.
break; // This isn't even in the loop!
In other words, the point where you're trying to add your break (based on a comment you left on another answer) is outside the loop, which is why your code is running indefinitely.
Now, it sounds like you're really just trying to use a do/while to emulate an if statement, presumably as a challenge to yourself. If that is the case, do yourself a favor and give up on that idea.
You cannot use a do/while loop to emulate an if condition, because do will always run at least once. The only way you could ensure that it runs exactly once under a specific condition (i.e., what if does) would be by embedding an if statement inside the do loop, which would defeat the purpose of the exercise.
That said, you can emulate an if with a while:
while (condition)
{
// Execute code once.
break; // Then just quit.
}
Looking at this one piece:
do Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
while (textBox1.Text == "Andrea");
...what do you expect to happen if textBox1.Text == "Andrea"?
What the program is doing is checking your comparison test, then if it's true, it does what is inside of the do / while block, then it checks the comparison test, then if it's true, it does what is inside of the do / while block, then it checks the comparison test, then if it's true, it does what is inside of the do / while block, then...
Get the point?
You use do / while loops if the condition is going to change inside the loop (or you explicitly break out of it).
What you want instead is to change it to something like
if( textBox1.Text == "Andrea" )
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
Just a guess, but as FacticiusVir says, you probably want to use conditionals instead of loops:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "Andrea" || textBox1.Text == "Brittany")
{
Commission.Text = (Convert.ToDouble(textBox2.Text) / 10).ToString();
}
else
{
MessageBox.Show("The spelling of the name is incorrect", "Bad Spelling");
}
}

Categories