C# If statement, multiple conditions - c#

I was creating an averaging program in C# just to make sure I got array's.
What I'm trying to do is ask the user if they want to average whole numbers, or non whole numbers. I thought an If statement would be appropriate.
But the problem is, I dont know what operator to use for MULTIPLE conditions, I think this is best explained by seeing the code. (Even I'm getting confused now D:)
Console.WriteLine("\n Do you want to average whole numbers, or non-whole numbers? \n");
if (Console.ReadLine() == "whole numbers" && Console.ReadLine() == "Whole numbers")
{
Console.WriteLine("You chose whole numbers.");
}
My confusion occurs at the "Condition" && "Condition2" bit. I don't know if && is the correct operator, and C# certainly doesn't think so!
I've looked across the C# MSDN Operator list, but couldn't really understand which one to use...
P.S: The whole reason I'm doing the multiple conditions is because of capital letters ETC, if any of you knew how to combat that with a way to disregard caps and other error prone user ticks, then please tell me :D

Console.ReadLine reads input from the console. When the user presses enter, it returns a string. In your code it will ask twice from user to enter something if the first condition was true. So, the other one is redundant.Because you have used && operator, which is conditional AND operator, but you must use conditional OR statement(||). So, you have two choice:
Either assign Console.Readline() result to some variable and use this inside if statement, but change && to ||.
Or use string.Equals(String, String, StringComparison) overload, to find if two strings are equal case-insensitively
In first case, you can check as many conditions as you can. But of course these are redundant. You can compare entered string with whole numbers case insensitively with the second approach:
if (string.Equals(Console.ReadLine(), "whole numbers", StringComparison.CurrentCultureIgnoreCase))
{
Console.WriteLine("You chose whole numbers.");
}

Rather than testing for every variation in capitalization, maybe consider using the String.ToLower() method to convert the string for comparison to lowercase. Basically, by calling this method, the string that you use to call the method is converted to all lowercase letters. By using this, you make your program less prone to failure by means of capitalization.
Example:
string UserDecision = (Console.ReadLine()).ToLower();
if(UserDecision == "whole numbers")
{ // perform task }
In my example, I used Console.ReadLine() to get the user's input and then I immediately converted it to lowercase before storing it into the variable. This makes it much easier to compare strings.
In the case of which operator to use:
|| is the OR operator (ONLY ONE condition must be true)
&& is the AND operator (BOTH conditions must be true)

Related

Using a '||' logical OR operator for comparing strings [duplicate]

This question already has answers here:
if statements matching multiple values
(16 answers)
Closed 12 days ago.
I have written a simple conditional statement, in which I'm getting a string input from the user, checking if it's equal to something but the nature of my code makes me add a single more operand to operate between
I tried this but it gives an error that you can't operate between two strings, obv there is some logical fallacy but I want a similar solution to this problem
if (Console.ReadLine() == ("s"||"S"))
Now I know this works if I make a separate variable and just check with it for both "S" and "s", but I want to do it inline and within that single statement, If I add another "Readline()" it will just take two inputs and won't do what I want it to do.
If there is anyway to make this work within that line, please let me know.
You have to declare the variable outside the condition, but you can do everything else in one line.
You can use is to make it slightly more readable (but only works for literal comparison).
string input;
if ((input = Console.ReadLine()) is "s" or "S")
Or if you have to use == then
string input;
if ((input = Console.ReadLine()) == "s" || input == "S")
Would I suggest doing this? No. Do the sane thing by not cramming all this logic in one line.
string input = Console.ReadLine();
if (input is "s" or "S")
What about trying
if (Console.ReadLine().ToLower() == "s")

Splitting a string based on specific characters

I will try to describe my problem as well as I can.
I am trying to write a program that will handle equations like:
F = (X∨A) ↔ (X∨B) ( (X OR A) is equivalent to (X OR B) )!
I have to solve it by 'X', or to better say, write disjunctive and/or conjunctive normal form.
So, theoretically, it goes like this:
When the truth table is written, you have to see when F is equal to 1 (tautology), and write conjunctive/disjunctive normal form.
For example (disjunctive normal form for the given table):
For A=0,B=0 and A=1,B=1, the value of X does not matter, and for A=0,B=1 AND A=1,B=0, X must be 1.
In the end,
X=A∨B.
Since I'm writing it in C#, equations are written in a TextBox.
What bothers me,is how should I separate my string so I can solve it part by part?
What about first trying "Split()" method (or other methods) of the class String in C#? In the first place, you'd better push your users to insert a blank (as the separator of Split()) between each pair of tokens (e.g. A AND B) , so that you can concentrate on the main logic of your solver.
I see. It's basically a simplifying calculator that doesn't (necessarily) have sequential input via buttons but a ready-made formula typed or pasted in a textbox.
What you need to do is therefore
define a set of permitted operators (AND, OR, NOT, XOR, etc.) in
various permitted notations (Λ, V, !, =, !=, etc., +,*,-,=, ↔ etc.)
check whether the input is syntactically correct; which means
you'll probably have to first remove all spaces from the input
string, then use regular expressions for allowed constructs, which
will probably prove to be a pain
if input is valid, check for parentheses first to determine grouped
expressions
simplify according to boolean algebra
Or simply follow this link (Java but still): Boolean expression solver/simplifier, use the tool bc2cnf or any other library that is linked there and spare yourself a lot of headache by restricting the permitted input to one permitted by the used library.
Hope this helps.

Input String is not correct format when trying to type in a hyphen first

I am trying to put a negative number in a textbox, however whenever i click on the textbox and try to type for they hyphen it creates the error, also I don't want it to create this same error if i accidentally leave the textbox blank. as it has done before
TextBox tbox = this.Controls.Find("Team" + r.ToString() + "Q" + c.ToString(), true).FirstOrDefault() as TextBox;
int t1 = Convert.ToInt32(tbox.Text);
if (r == 1) team1score += t1;`
Yes, it's probably because when you type -, the CalculateTotals method is called and it tries to convert - to an integer, and fails. You don't show how you're doing the conversion, which is the most important part of your code. You probably should do something like this:
int myInt;
if (!int.TryParse(senderTB.Text, out myInt))
{
// The value in the textbox isn't an integer.
// Use 0 as the default.
myInt = 0;
}
That's not entirely correct, though, because the user might type something like 4000000000, which is larger than an int.
A quick fix would be to modify your regular expression so that it requires at least one number:
Regex reg = new Regex(#"^-?[0-9]+$");
Replacing the * with a + won't allow just a hyphen to match. This will fix your immediate problem, but it's not complete error checking. But it might be good enough for your purposes.
In general, you can easily use regular expressions to validate the form of a signed integer (i.e. an optional hyphen followed by one or more digits), but it's very difficult to use regular expressions to make sure the number is within the range of a signed integer. Making sure that the number is not less than -2147483648 or greater than 2147483647 is rather difficult to do with regular expressions.
You probably want a combination of the approaches: use the regular expression to prevent the user from typing illegal characters into the text box, and use int.TryParse to validate the number in your computeTotals method. And rather than defaulting to a value of 0, have the program display a message box informing the user of the error.

How to validate a excel expression programmatically

I have been developing an application that one of it's responsability is provide to user an page that it's possible to write math expression in EXCEL WAY.
It is an application in ASP.NET MVC, and it's use the SpreadSheetGear library to EXECUTE excel expression.
As it's show below, The page has an texarea to write expression and two button on the right. The green one is for VALIDATE THE EXPRESSION and the red one is for clean textarea.
A,B,C are parameter, that application will replace for values. Notice that it is not possible to know the parameter data type. I mean, if I write a concatenate function, It is necessary that user use double quotes (") to delimitate string. For example
CONCATENATE("A","B") thus, is necessary that user KNOW functions parameters and its correlate data types.
My main issue is how to validate the expression?
SpreadSheetGear there isn't any method to perform this validation.
The method spreadsheetgear provides to perform an formula is:
string formula = "{formula from textarea}"
worksheet.EvaluateValue(formula)
and it's expect and string.
As I don't know what formula user will write, or how many parameters this formula has and what are the parameters data type, it's kind difficult to validate.
Now my question is?
How could I validate the expression?
I think in an alternative: Provide to user and page with textbox for each parameter in the expression. The user will be able to provide some data and validate the RESULT of formula. If the sintaxe of formula is wrong the application throw an exception.
It would be a good solution, but for each "PROCESS" that user will interact to, He'll write 10, 15 formulas, and maybe it would be little painful.
Anyone could provide me an Good solution for that?
Thank you!
https://sites.google.com/site/akshatsharma80/home/data-structures/validate-an-arithmetic-expression
refer this site for validation
This is a very late response but I have been working on expression evaluators in Excel with VBA for a while and I might shed some light. I have three solutions to try but all have limitations.
1) Ask the user to put a '$' after a variable name to signify a string (or some other unique character). Drawback is that it is not as simple as typing a single letter for a variable.
2) Assume all variables entered are double precision. Then change the variable to strings in all combinations until one combination works. Could be very time consuming to try all the combinations if the user enters lots of individual variables.
3) Assume all variables entered are double precision. But then have a list in your program of functions that require strings for parameters. Then you could parse the expression, lookup the functions in your list and then designate the parameters that require string input with a string signifier (like in step 1). This will not account for user defined functions.
Now to test out the function, replace all the numeric variables with '1' and all the string variables with "a", then EvaluateValue. If you get a result or an error signifying a calculation error, it is good.
BTW, in order to parse the expression, I suggest the following method. I do not know C#, only VB, so I will only talk in general terms.
1) Take your expression string and do a search and replace of all the typical operators with the same operator but with a backslash ("\") in front and behind the operator (you can use any other character that is not normally used in Excel formulas if you like). This will delineate these operators so that you can easily ignore them and split up your expression into chunks. Typically only need to delineate +,-,/,*,^,<,>,= and {comma}. So search for a "+" and replace it with a "\+\" and so on. For parenthesis, replace "(" and ")" with "(\\" and "\\)" respectively.
So your sample formula "SUM(A, SQRT(B, C)) * PI()" will look like this:
"SUM(\\A\,\ SQRT(\\B\,\ C\\)\\) \*\ PI(\\\\)"
You can also clean up the string a bit more by eliminating any spaces and by eliminating redundant backslashes by replacing every three consecutive backslashes with a single one (replace "\\" with "\").
2) In Visual Basic there is a command called 'Split' that can take a string like this and split it into a one dimensional array using a delimiter (in this case, the backslash). There must be an equivalent in C# or you can just make one. Your array will look like this: "SUM(", "", "A", ",", "SQRT(", "", "B", etc.
Now iterate through your array, starting at the first element and then skipping every other element. These elements will either be a number (a numeric test), a variable, a function (with have a "(" at the end of it), a parenthesis or blank.
Now you can do other checks as you need and replace the variables with actual values.
3) When you are done, rejoin the array back into a string, without any delimiters, and try the Evaluate function.

RegEx expressions with replacement and extracting values

I want to take an expression like
(123456789..value > 2000) && (987654321.Value < 12)
extract the 123456789 and 987654321 (could be anything here)
and replace it with
ClassName.GetInfo("%s").GetValue() (as an example)
putting the 2 values in the place of the %s...
to be a resulting
(ClassName.GetInfo("123456789").GetValue() > 2000) && (ClassName.GetInfo("987654321").GetValue() < 12)
Can anyone give me a clue as to how to accomplish this?
A rather oversimplified example, but this should work.
Note that the following will only allow alpha-numeric or '-' or '_' in the place you claim (could be anything here). This is by nessesity if you intend to be able to recognize it with any form of parser regex or otherwise. You need to either limit the characters that can be used as an identifier, or you need to delineate them and allow for escaping the delimitation characters.
private static void Main()
{
Regex pattern = new Regex(#"(?<Name>[\w\-_]+)\.+(?<Value>[\w\-_]+)");
string sample = #"(123456789..value > 2000) && (987654321.Value < 12)";
string result = pattern.Replace(sample,
m =>
String.Format(
"ClassName.GetInfo(\"{0}\").Get{1}{2}()",
m.Groups["Name"].Value,
Char.ToUpper(m.Groups["Value"].Value[0]),
m.Groups["Value"].Value.Substring(1))
);
Console.WriteLine(result);
}
The program outputs:
(ClassName.GetInfo("123456789").GetValue() > 2000) && (ClassName.GetInfo("987654321").GetValue() < 12)
There are two other rather odd behaviors in your example that are addressed above. The first is the use of multiple delimiters '..' in your example "(123456789..value". This seems like a possible mistake, just remove the '+' from this part of the expression ").+(".
The second oddity is that your example just auto-magically corrects the character-case of the first property from "value" to "Value". Although I mimic this magical behavior by ensuring the first character is upper-case this is not a great solution. A better answer would be to use a case-insensitive dictionary and lookup the proper case.
Hopefully that will get you started, but I have to be honest and say you have a VERY long road ahead of you. Parsing an expression language is never a trivial thing and should generally be avoided. If this is for internal use just make them type in the full version. If this is for external use... well, I would re-think you're objective. Perhaps building a graphical expression tree like SQL's QBE would be a better expenditure of your time and energy.

Categories