string number = txtNumber.Text;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
break;
}
else
{
MessageBox.Show("Account Number not found");
}
}
Hello everyone, I'm fairly new here and with C# . So I have a class Account with client info which is stored in a text file.I want to loop through the array tabAccounts[200] and look if the entered user number corresponds to one that is in the text file. It works fine but when i enter let's say 222 it starts looping from the begging until it finds the number and if it doesn't it just keep looping and the message "Account Number not found" keeps coming out. When i remove the else statement it works fine but I want it that when a user enters a wrong number a message box will show...Hope you guys get it :( Tried googling but didnt find anything..
This can be done much more effective with LINQ:
var account = tabAccounts.SingleOrDefault(a => a.Number == txtNumber.Text);
if(account != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + account.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
For your original code: The problem is that you are displaying the message inside the loop, every time the loop didn't find anything. This is a rewrite close to your original syntax, just to show you how to do it:
Account foundAccount = null;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
foundAccount = ac;
break;
}
}
if(foundAccount != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + foundAccount.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
The minimum change required to achive your goal:
string number = txtNumber.Text;
bool found = false;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
found = true;
break;
}
}
if (!found)
MessageBox.Show("Account Number not found");
The problem is that you don't wait until you've finished searching to display "Account Number not found", you show it every time you find an Account that doesn't match. I'd rewrite it like this, using the FirstOrDefault extension method.
string number = txtNumber.Text;
Account ac = tabAccounts.FirstOrDefault(x => x.Number == txtNumber.Text);
if (ac != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
The best way to do this would be to set a flag when you find the element and then display outside of the loop
bool found = false;
string client;
string number = txtNumber.Text;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
found = true;
client = ac.Client;
break;
}
}
if (found)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + client;
}
else
{
MessageBox.Show("Account Number not found");
}
Related
I have to show the abbreviations of the provinces of my country when the user types in the name, or show the name when the user types in the province. I have created the 2 arrays so that the indexes match and I am trying to use a for loop to search through the arrays and once they find a match then display the other arrays same index in a textbox. It works only for the first index and even with the first index shows the else error message. What am I doing wrong?
string[] statenames = new string[9] { "Eastern Cape", "Free State", "Gauteng", "KwaZulu-Natal", "Limpopo", "Mpumalanga", "Northern Cape", "North-West", "Western Cape" };
string[] abbreviations = new string[9] { "EC", "FS", "GP", "KZN", "LP", "MP", "NC", "NW", "WC" };
private void btnLook_Click(object sender, EventArgs e)
{
try
{
string name = txtName.Text;
string abbreviation = txtAbbreviation.Text;
if (rbtnAbbreviation.Checked == false && rbtnStateName.Checked == false)
{
MessageBox.Show("Please select what you would like to look up", "Entry Error");
}
if (rbtnAbbreviation.Checked)
{
for (int x = 0; x < statenames.Length; x++)
{
if (name == statenames[x])
{
txtAbbreviation.Text = abbreviations[x];
}
else
{
MessageBox.Show("Please enter a valid province name", "Entry Error");
txtName.Focus();
}
}
}
if (rbtnStateName.Checked)
{
for (int x = 0; x < abbreviations.Length; x++)
{
if (abbreviation == abbreviations[x])
{
txtName.Text = statenames[x];
}
else
{
MessageBox.Show("Please enter a valid province abbreviation", "Entry Error");
txtAbbreviation.Focus();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" + ex.GetType().ToString() + "\n" + ex.StackTrace, "Exception");
}
}
I think you should add a break to the if conditions. Once you find the name you want you get out of the loop.
if (abbreviation == abbreviations[x])
{
txtName.Text = statenames[x];
break;
}
in-order to prevent the loop from continue checking the rest of the array, and that's what cause the else to be triggered.
This is my code
public void showMatch (string guess, string regx){
int outputCode;
MatchCollection mc = Regex.Matches (guess, regx);
foreach (Match m in mc) {
listOfTags [ctr] = m.Value;
ctr++;
}
checkOpeningTag = listOfTags [0];
checkClosingTag = listOfTags [1];
if (checkOpeningTag.Equals ("<h1>")) {
if (checkClosingTag.Equals ("</h1>")) {
outputCode = 3;
} else {
outputCode = 2;
}
} else {
outputCode = 1;
}
showError(outputCode);
}
public void showError(int checkError){
if (checkError == 1) {
error.text = "Sorry, no opening tag found.";
} else if(checkError == 2){
error.text = "Sorry, no closing tag found.";
}else if(checkError == 3){
error.text = "You got it right! Advancing to next level!";
}
}
If I try to input <'h1'> and <'h1'> (disregard ') , it will give me an error of
Sorry no opening tag
But when I try to correct it by submitting <'h1'> and <'/h1'> (disregard '), the error won't update. It still says Sorry no opening tag.
I tried using this code at the end of showMatch function
Debug.Log(outputCode);
I found that if the first input result is 2, the result everytime will always be 2. Same with if 1 is the result, the next results will be 1.
What am I doing wrong?
I have spent a fair few hours on this problem, it's quite basic but has gotten out of hand quickly.
Because it is rather confusing I'll post what I want it to do and what it actually does
Goal
If a supervisor is busy, it will move onto the next one, if they are all busy it will display a message "Sorry all supervisors are busy". Likewise with all employees.
Method
I want the method to read all the supervisors, if one is not busy it continues down, then I want it to read all of the employees, if one is not busy it continues down.
Then it reads if the employee has the appropriate skill and if the success has already been met, to avoid the same person being assigned the same job.
if this is all good so far, it checks if the supervisor is occupied, if it is, it reverts back and changes supervisor.
It then assigns the employee with the information, also assigning the supervisor with some and checking the 'success' condition.
From here it starts to get a bit sloppy, as you can see, I have put numerous boolean statements to simply get the program out of the loops and exit it.
After all of this, the program assigns the work, so far, it works to a reasonable degree, but I want there to be a message that states that if all of the supervisors are busy that no more work can be allocated.
I have in the past, used MessageBox.Show after foreach statements but if one supervisor is busy it will display the message which is not what I want.
Code
Method to distribute a job
bool finishLast = false;
bool successFirst = false;
while (successFirst != true)
{
foreach (Supervisor sup in supervisors)
{
bool failure = false;
while (failure != true)
{
foreach (Employee emp in employees)
{
if (emp.Busy == false && emp.Skills.HasFlag(_skillRequired) && successFirst == false)
{
if (sup.SupervisorOccupied == false)
{
successFirst = true;
emp.EmployeeWorkload = _jobName;
emp.ShiftsLeft = _shiftsLeft;
emp.Busy = true;
sup.EmployeeWorkload = "Supervising Employee: " + emp.EmployeeName + " to finish task: " + emp.EmployeeWorkload;
sup.ShiftsLeft = _shiftsLeft;
sup.SupervisorOccupied = true;
}
}
else if (emp.Busy == true)
{
failure = true;
}
}
}
if (failure == true)
{
finishLast = true;
}
}
if (finishLast == true)
{
successFirst = true;
}
}
Of course if anyone can think of a simpler way of having this I will be open to ideas.
EDIT 1
This is not a multi-threaded system, yes emp.Busy and sup.SupervisorOccupied are technically the same thing, they are both in the same class so yes sup could inherit emp.Busy.
I think something like this should work:
bool assigned = false;
foreach (Supervisor sup in supervisors)
{
if (!sup.SupervisorOccupied)
{
foreach (Employee emp in employees)
{
if (!emp.Busy && emp.Skills.HasFlag(_skillRequired))
{
assigned = true;
emp.EmployeeWorkload = _jobName;
emp.ShiftsLeft = _shiftsLeft;
emp.Busy = true;
sup.EmployeeWorkload = "Supervising Employee: " + emp.EmployeeName + " to finish task: " + emp.EmployeeWorkload;
sup.ShiftsLeft = _shiftsLeft;
sup.SupervisorOccupied = true;
break;
}
}
}
if (assigned)
break;
}
if at the end "assigned == false", no employee is available (actually there's some code missing so it can't run, but theoretically it should do what you want!).
Here's how you should write that code:
var availableSupervisor = supervisors
.FirstOrDefault(supervisor => !supervisor.SupervisorOccupied);
if (availableSupervisor == null)
return;
var availableEmployee = employees
.FirstOrDefault(employee => !employee.Busy && employee.Skills.HasFlag(_skillRequired));
if (availableEmployee == null)
return;
availableEmployee.EmployeeWorkload = _jobName;
availableEmployee.ShiftsLeft = _shiftsLeft;
availableEmployee.Busy = true;
availableSupervisor.EmployeeWorkload = "Supervising Employee: " + emp.EmployeeName + " to finish task: " + emp.EmployeeWorkload;
availableSupervisor.ShiftsLeft = _shiftsLeft;
availableSupervisor.SupervisorOccupied = true;
I'm trying to create textbox where you can enter your name.
If textbox is empty show error.
If textbox contain numbers show error.
In my sample it does show error when i have empty textbox and when i have numbers like Robert1. But it does not work when Text ends with a letter. If you write 1Robert, then it doesn't show error.
My code:
string vards = textBox1.Text;
// Empty or wrong format
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
label5.Text = "You didn't enter anything!";
}
else
{
foreach(char c in vards)
{
if (Char.IsNumber(c))
{
label5.Text = "Your name is incorrect!";
}
else
{
label5.Text = "";
}
}
}
I guess i just had to add break;
if (Char.IsNumber(c))
{
label5.Text = "Your name is incorrect!";
break;
}
the loop produces a invalid result. it overwrites the content of label5 each char of label1 and the final result is only about the last char
// Empty or wrong format
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
label5.Text = "You didn't enter anything!";
}
else
{
bool onlyLetters = textBox1.Text.All(x => Char.IsLetter(x));
if (!onlyLetters)
{
label5.Text = "Your name is incorrect!";
}
else
{
label5.Text = "";
}
}
You are using a loop on every character in the text. There you are overwriting label5.Text always. So actually only the last character matters in your logic.
You can use this:
bool anyNumbers = textBox1.Text.Any(Char.IsDigit);
if(anyNumbers)
{
label5.Text = "Your name is incorrect!";
}
Here without LINQ:
bool valid = true;
foreach (char c in textBox1.Text)
{
if (char.IsDigit(c))
{
valid = false;
break;
}
}
You could do the following:
var input = txtExample.Text;
if(!string.IsNullOrEmpty(input))
if(input.Any(d => char.IsDigit(d) == false)
{
// Valid
}
You could actually use Linq, not even use the foreach loop. Keep in mind this is being done on the server side, if your in a web application you trigger a PostBack. Which you may want to do that, so if it is web based, you should do it Client Side.
Im making a chat program that saves the messages in files like pub0.zzc, all computers that are using it will be connected to the hard drive that these files are in, so its fine. The method data.Chat.Read(MessageTypes type, string Channel) infinite loops through a try catch statement till it returns the messages. I used this before and works perfectly. But, my code was hard to manage so instead of just putting text boxes into the window and using the code each time, i created a user control (MessageViewer). It works fine, once again when I run it, BUT it freezes VS whenever I try to use the designer on the window housing the control. the probelm isnt the window because when i delete the control its fine. I think the possible errors are at RefreshMessages() and the Refresher_Tick(...)
Refresher.Stop() and .Start() is also not it, worked fine before
so here is the code:
private void Refresher_Tick(object sender, EventArgs e)
{
Refresher.Stop();
int RefreshRate = 4;
bool Live = true;
if (RefreshRateChoice == "Manual")
{
Live = false;
RefreshRate = 1;
}
else if (RefreshRateChoice == "4 ( Default )")
{
Live = true;
RefreshRate = 4;
}
else
{
Live = true;
RefreshRate = Convert.ToInt32(RefreshRateChoice);
}
if (data.Chat.Read(MessageType, ChannelChoice) != ContentPresenter.Text && Live)
{
RefreshMessages();
}
Refresher.Interval = RefreshRate;
Refresher.Start();
}
public void RefreshMessages() {
if (data.Chat.Read(MessageType, ChannelChoice) != ContentPresenter.Text)
{
ContentPresenter.Text = data.Chat.Read(MessageType, ChannelChoice);
}
}
and if you need it:
public static string Read(MessageTypes Type, string Channel)
{
string Loc;
if (Type == MessageTypes.Public && (Channel == "1" || Channel == "2"))
{
return "Can not view this channel, only post to it.";
}
if (Type == MessageTypes.Public)
{
Loc = data.AssetsFolder + "\\pub" + Channel + ".zzc";
}
else if (Type == MessageTypes.Private)
{
Loc = data.AssetsFolder + "\\" + Channel + ".zzpc";
}
else if (Type == MessageTypes.Game)
{
Loc = data.AssetsFolder;
}
else
{
Loc = data.AssetsFolder;
}
while (true)
{
try
{
String MessageList = "";
StreamReader MessageReader = new StreamReader(Loc);
string EncMessages = MessageReader.ReadToEnd();
MessageReader.Dispose();
List<string> EncMsgList = EncMessages.Split(';').ToList();
for (int i = 1; i < EncMsgList.Count; i++)
{
MessageList += data.Encodings.Decrypt(EncMsgList[i], Palettes.Message) + "\n";
}
return MessageList;
}
catch
{
// Do nothing
}
}
}
You say that it "freezes."
In your Read method you have a while(true) loop with an embedded try...catch block, but the catch never returns you from that method. If you keep throwing the same exception, you'll continue to loop over and over which could be where you are freezing.
At least to prove that is the case, put a return in you catch or some diagnostic code to indicate if that is the case.