How can I retrieve my result everytime in Unity using C#? - c#

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?

Related

compare the items in list in c#

i want to compare the selecteditem of combobox with the selecteditem of other combobox
for this i have registered all the comboboxes in a list and named it "panel1kilist"
now the problem i am facing is that when there are same items in two comboboxes first the messagebox shows "no mattch found" and then it shows "match found" actually it goes to the else statement of inner loop first and then to if statement kindly help
private void button1_Click(object sender, EventArgs e)
{
bool check = false;
bool check1 = false;[![in this image you can see that there are two same items but message is showing "no match found"][1]][1]
try[![after clicking on ok button of message box showing "no match found" this message box shows up][1]][1]
{
for (int i = 1; i < panel1kilist.Count; i++)
{
for (int j = i + 1; j < panel1kilist.Count; j++)
{
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
}
}
}
catch (System.NullReferenceException)
{
MessageBox.Show("please fill all the boxes first");
}
}
Your question is not really clear but I still try to give you some help. As mentioned in the comments there are several small issues in your code:
1. The outter for-loop
for (int i = 1; i < panel1kilist.Count; i++)
You define i = 1, which means you skip the very first item in your panel1kilist because lists and arrays start at index 0
2. Use of your bool variables
if (panel1kilist[i].SelectedItem.ToString() == panel1kilist[j].SelectedItem.ToString())
{
if (check == false)
{
MessageBox.Show("match found");
}
check = true;
}
else
{
if (check1 == false)
{
MessageBox.Show("no match found");
}
check1 = true;
}
You define your bool variables before starting your for-loops. So whenever you set your variables check and check1 to true, the if conditions check == false and check1 == false will never return true anymore. So you will never get any message except the very first "Match found" and "no match found".
3. My proposed solution
Make use of the foreach-loop and break the loops once you found a match, after the loops just show the message. Code:
var matchFound = false;
foreach (var combobox in panel1kilist)
{
foreach (var comboboxToMatch in panel1kilist.Skip(1))
{
if (combobox.SelectedItem.ToString() == comboboxToMatch.SelectedItem.ToString())
{
matchFound = true;
// Stops the inner loop in case of a match
break;
}
}
// Stops the outer loop in case of a match
if(matchFound)
{
break;
}
}
if(matchFound)
{
MessageBox.Show("match found");
}

C# string processing and condition

I am reading and storing CMD commands in an array.
The last line in the array is the following string:
"[1] success"
I want to extract the 'success' part. So I stored the last element in a new variable and did some transformation:
var item = line[line.Count - 1];
item = item.Replace("[1]", "");
item = item.Replace("\"", "");
and then I do the following condition:
if (item == "success")
{
MessageBox.Show("Successful processing");
}
else
{
MessageBox.Show("There was an error.");
}
When I do MessageBox.Show(item); the exact characters I need are printed - success.
Nonetheless, the condition always returns the else output. I don't understand why?
Just check to see if item contains "success":
var item = line[line.Count - 1];
if (item.Contains("success"))
{
MessageBox.Show("Successful processing");
}
else
{
MessageBox.Show("There was an error.");
}
You can just use Contains like this:
if(line[line.Count - 1].Contains("success"))
{
MessageBox.Show("Successful processing");
}
else
{
MessageBox.Show("There was an error.");
}
You can simply use IndexOf:
if(line[line.Count - 1].IndexOf("success") > -1)
{
MessageBox.Show("Successful processing");
}
else
{
MessageBox.Show("There was an error.");
}
There is a space at the start of your variable value. Try calling Trim() first and then compare.
var item = line[line.Count - 1];
item = item.Replace("[1]", "");
item = item.Replace("\"", "");
item = item.Trim();

Is there a way to use a variable in a catch block that was previously assigned in a try block?

So I've just been making a basic little calculator made up of buttons and a textbox(tbxSum).
The problem I'm having is that if an invalid sum is input I want my catch block to pick it up(which it does) and replace what's in the textbox with the most recent result in the calculator(which it doesn't).
So say I say:
3+3=6
My calculator will now put 6 in the textbox for the next sum.
So then say I did:
6//3
It's invalid which the calculator picks up, but I want the textbox value to return to 6 from the previous sum.
This is what I've tried:
var myButton = (Button)sender;
if (myButton.Content.ToString() == "=")
{
DataTable dt = new DataTable();
string s = tbxSum.Text;
string result = "";
if (s.Contains("("))
{
s = s.Replace("(", "*(");
}
try
{
var v = dt.Compute(s, "");
tbkSum.Text = s + "=" + v.ToString();
tbxSum.Text = v.ToString();
}
catch
{
MessageBox.Show("Invalid Sum");
tbxSum.Text = result;
}
}
I also have a textblock(tbkSum) which shows the previous sum so I thought maybe I could take everything in there to the right of the equals sign but I have no idea how to do that.
class Calculate(){
private boolean lastGoodValueSet = false;
private int lastGoodValue = 0;
void buttonFunction(){
if (myButton.Content.ToString() == "=")
{
//Your code
try
{
var v = dt.Compute(s, "");
tbkSum.Text = s + "=" + v.ToString();
lastGoodValue = v;
lastGoodValueSet = true;
}
catch
{
MessageBox.Show("Invalid Sum");
tbxSum.Text = result;
if (lastGoodValueSet)
tbxSum.Text = lastGoodValue;
}
}
}
}
This is an example set of code you could use, it's a simple value that you have to store to say if a good computation has been done and if so, at the point of error we want to go back to the computation. Hope that helps! You'll want to put some kind of message to the user, so they know there was an error though.
We have to do this, as at the point of the user pressing the equals button, the value has already changed inside tbkSum, we need it before the user has changed the value, so the best time to grab it is at the point when we update the tbkSum text value at a successful calculation
This is also assuming you do not create a new instance of the Calculate class each time you do your computation. Otherwise you'd need to store the number somewhere else
EDIT
The other way to fix this issue is to instead prevent the duplicate in the first place, I read from your other comments that you control what goes into the text box by buttons on the application. Assuming all buttons go through the same method of buttonFunction() then you could do:
private char[] buttonChars = {'/','*', '+'/*e.t.c*/}
void buttonFunction(){
string buttonPressedStr = myButton.Content.ToString();
char buttonPressed = buttonPressedStr[0];
int pos = Array.IndexOf(buttonChars , buttonPressed);
if (pos > -1)
{
if (tbxSum.Text.Length > 0){
char last = tbxSum.Text[tbxSum.Text.Length - 1];
pos = Array.IndexOf(buttonChars , last);
}
else
pos = 0;
if (pos > -1){
tbkSum.Text += buttonPressedStr;
}
}
There are cleaner ways to do this, but it's an example of how you could have prevented your issue in the first place. Some explanation:
buttonChars is an array of your different button types that would be appended to your text in the box, an example is +, -, and so on
First it checks if the button pressed was in your collection of specified buttonChars
If so, we have to check what the last thing added to the tbxSum was
If the last thing added to tbxSum was again found in the buttonChars array, we don't want to append a string
Otherwise, if the tbxSum was empty or had another character at the end, we can append our character
You can store the old value in a variable declard outside the try block and use this variable in your catch block again:
string oldSumValue = tbxSum.Text;
try
{
// your code
}
catch
{
tbxSum.Text = oldSumValue ;
MessageBox.Show("Invalid Sum");
}
Alternatively I've come up with this to prevent there being:
A)Duplicate of '*' or '/'
B)Sum starting with '*' or '/'
public MainWindow()
{
InitializeComponent();
if (tbxSum.Text == "")
{
btnDiv.IsEnabled = false;
btnMult.IsEnabled = false;
}
}
protected void btnSumClick(object sender, EventArgs e)
{
btnDiv.IsEnabled = true;
btnMult.IsEnabled = true;
var myButton = (Button)sender;
int pos = tbxSum.Text.Length;
if (pos > 0)
{
if ((tbxSum.Text[pos - 1] == '/' || tbxSum.Text[pos - 1] == '*') &&
(myButton.Content.ToString() == "/" || myButton.Content.ToString() == "*"))
{
int location = tbxSum.Text.Length - 1;
tbxSum.Text = tbxSum.Text.Remove(location, 1);
}
}
}

Textbox can contain letters but no numbers allowed

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.

Looking for a specific info in a loop

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");
}

Categories