I have 2 textboxes on my form for which I'm trying to restrict the input. Here is a more detailed description of what I'm trying to do:
Code a method named IsValidData that checks that the Operand 1 and Operand 2 text boxes contain a decimal value between 0 and 1,000,000 (non-inclusive) and that the Operator text box contains a valid operator.
I know the way that I did this is wrong but I'm not sure how to fix it. The way I thought of it when writing the if statement is this:
check to make sure the value is >0 AND <=100 for the input in the txtOperand1 textbox and then did the same for the other textbox. Can someone please give suggestions on what I'm doing wrong? Thanks.
double operand1 = Convert.ToDouble(txtOperand1.Text);
double operand2 = Convert.ToDouble(txtOperand2);
if ((operand1 > 0 && operand1 <= 100) &&
(operand2 > 0 && operand2 <= 100))
return true;
something like this?
return decimal.TryParse(txt.Text, out decimal val) && (val > 0m & val < 1000000m)
Related
This question already has answers here:
How to elegantly check if a number is within a range?
(33 answers)
Closed 1 year ago.
Trying to check if an integer value falls into a range however it is giving me a compile time error
Operator '<=' cannot be applied to operands of type 'bool' and 'int'
int n = 3; // read from user like Convert.ToInt32(Console.ReadLine().Trim());
if ( 2 <= N <= 5)
{
Console.WriteLine("In range");
}
What is the correct way to check if a value falls into a range and why the way I wrote the check causes this error?
You can't do this:
(2<=N<=5)
You have to do it as two:
(2<=N && N<=5)
(Trying to do it as one means c# will resolve the 2<=N to some boolean, e.g true and then try to do true<=5 - this gives rise to the error that "<= cannot be used to compare a boolean to an integer")
This doesn't work they way you think it does:
(2<=N<=5)
What really happens here is the compiler first evaluates the 2<=N part of the expression as producing a boolean result. It then wants to use this boolean result for the <=5 part of the expression... and that's not allowed. C# does not let you implicitly compare a boolean with an integer, and even if it did it's doubtful the result would match your intention for the code.
Instead, you need to do this:
if( (2 <= N && N <= 5) || N > 20 )
The same applies to the 6<=N<=20 expression.
Finally, I might reduce the logic to eliminate nesting and repeated outcomes, like this:
int N = Convert.ToInt32(Console.ReadLine().Trim());
if(N % 2 !=0 || (6 <= N && N <= 20 ))
{
Console.WriteLine("Not Weird");
}
else if( (2 <= N && N <= 4) || N >20 ) //4 rather than 5, because we know N is even
{
Console.WriteLine("Weird");
}
else // N is even and <=0
{
Console.WriteLine();
}
I am debugging a "Guess the Number" program between 1-100. The first user creates a secretNumber and the second user guesses the number.
I'm trying to check if the second user input is a number between 1-100, but it still accepts negative numbers for some reason, and I can't figure out why.
Please note I am very new to coding, so I'm not well-versed with the jargon yet. In my class, we have just learned while loops and relational operators and if/else statements, so I am only allowed to use those.
The (secretNumber == 0) is to make sure int.TryParse() doesn't return 0 if the user typed in letters instead of numbers.
if statement checking:
( secretNumber >= 1 && secretNumber <= 100 )
and also
( secretNumber >= 1 || secretNumber <= 100 )
This is my code:
//Create a number variable to hold the whole number
int secretNumber;
//Validate that the number is a whole number AND between 1 and 100
if ( int.TryParse(secretNumberString, out secretNumber)
|| ( secretNumber >= 1 && secretNumber <= 100 )
|| secretNumber == 0 )
{
// Tell the user the problem
Console.WriteLine("Sorry, please only type in whole numbers and it must be between 1 and 100!");
// Re-ask the question
Console.WriteLine("What is your secret number?");
// Re-catch the response in the same variable
secretNumberString = Console.ReadLine();
// Re-assign the new input
int.TryParse(secretNumberString, out secretNumber);
}
The if statement should run if the user inputs a negative value.
It runs if the user types a value above 100, but it doesn't run if the value is below 100. Otherwise, it shouldn't run if the number is correctly between 1-100.
The statement must be true if the input is either non-numeric or outside 1~100 range. Is that correct?
//if string is NOT integral (notice the !) Or less than 1 Or bigger than 100
if (!int.TryParse(str, out int secretNumber) || secretNumber < 1 || secretNumber > 100)
Also, the user could still input non-integral, out-of-range number at the second attempt as it is not validated. Ideally, I believe it's better to put the validation logic as a loop variable:
string input;
int secretNumber;
do
{
Console.WriteLine("Input an integer between 1 and 100, inclusive.");
input = Console.ReadLine();
}
while (!int.TryParse(input, out secretNumber) || secretNumber < 1 || secretNumber > 100);
The problem is your || (or), this is just a simple Boolean Algebra (Propositional Logic) mistake, it needs to be && (and)
However, a similar neater pattern is a condensed validation loop
var num = 0;
Console.WriteLine("What is your secret number between 1 and 100 inclusively?");
var str = Console.ReadLine();
// while its not a number, "or" the number is less or equal to 0 "or" greater than 100
// annoy them with a message
while (!int.TryParse(str, out num ) || num <= 0 || num > 100)
{
Console.WriteLine("Omg you had one job, a number between 1 and 100 inclusively... Try again");
str= Console.ReadLine()
}
Console.WriteLine($"You won, your number is {num } ");
You might want to read the documentation for int.TryParse() — it returns true if the string was successfully parsed as an integer and false otherwise. Your test, int.TryParse( secretNumberString, out secretNumber ) || ( secretNumber >= 1 && secretNumber <= 100 ) || secretNumber == 0 ) will only ever test the value of secretNumber if the parse failed (at which point its value will be 0).
This might get you started:
static int GetAnswer( string prompt, int min , int max )
{
if (min > max) throw new ArgumentException("min must be less than or equal to max");
int value ;
bool valid = false ;
do
{
Console.WriteLine(prompt);
string answer = Console.ReadLine().Trim() ;
valid = int.TryParse(answer, out value)
&& value >= min
&& value <= max
;
if (!valid)
{
Console.WriteLine($"Sorry, please only type in whole numbers in the range {min}-{max}.");
}
} while (!valid );
return value;
}
I understand standard usage of ternary operator..
string message = hasError=="Y" ? "There's an error!" : "Everything seems fine...";
But how do I add an OR in the subexpression..
if((hasError=="Y")||(seemsfine=="N")){
message="There's an error!";
}else{message="Everything seems fine...";
}
Any help is sincerely appreciated
Thanks
You can do it like this
string message = hasError == "Y" || seemsfine == "N" ? "There's an error!" : "Everything seems fine...";
There is not much difference. This is because the ternary operator in C# is that handy!
Ultimately, it is the result of the whole expression (that is, hasError == "Y" || seemsfine == "N") that matters, not how many conditions you have. You can put all other conditions if you want too, as long as the whole expression return true then it will assign the first element (left of :) to the variable and when the whole expression is false it assigns the second element (right of :) to the variable
Ternary operator is completely equivalent with if-else statement whose block is simply to assign value to single variable.
Thus,
if (a1 == 0 || a2 > 5 || a3 <= -7)
b = 1;
else
b = 2;
is completely equivalent to
b = a1 == 0 || a2 > 5 || a3 <= -7 ? 1 : 2; //note that there is no bracket here, but it is equivalent to if-else statement with bracket
When you have more than single variable to be assigned, then the equivalent breaks.
if (a1 >= 0)
b = 2;
else
c = 3; //notice the variable difference, you cannot use ternary operator anymore.
As long as it does not hinder the readability of the code for you, you can even put multiple ternary operators like this
b = a1 > 0 && a2 < 0 ? 1 : (a3 < 5 ? 2 : 3);
which is equivalent to
if (a1 > 0 && a2 < 0)
b = 1;
else if (a3 < 5)
b = 2;
else
b = 3;
The initial expression can be as simple or as complicated as you need it to be, as long as the condition ultimately evaluates to a single boolean value, just like the first line of your if statement.
In other words, this:
if ((hasError == "Y") || (seemsfine == "N"))
message="There's an error!";
else
message="Everything seems fine...";
Is equivalent to this:
string message = (hasError == "Y" || seemsfine == "N")
? "There's an error!"
: "Everything seems fine...";
I have four text box A ,B,C and D.
Textbox A and B is user input field for example txtA = 250 ; txtB =300;
based on formula ((B-A/A)*100) i found value for C (%). After find the txtC (%20)value i have to find txtD.
To find out txtD, i have set of pre defined value to find txtD.
for example
if the % <10 then txtD=1
10-20 then txtD=2
20-30 then txtD=3 like wise until 100 %
. I am not sure whats the best approach to achieve this. i am just wondering create percentage table and handle or using switch statement is the best approach.
Why isn't it possible using simple if..else blocks?
Switch..Case is not appropriate when comparing range of values..
int D = (0.2 * C);
If (D < 10) {
txtD=2
}
elseif (D > 10 && D < 20){
txtD=3
}
elseif (D > 20 && D < 30){
txtD=4
}
..
if a textbox has 1 digit or a number that's larger than 31, the program will crash. how should I stop that?
so far, i have this code:
if (dd.Text.Length <= 1 || dd.Text > 31)
return;
obviously, that's wrong... :(
dd.Text > 31
The above code is comparing a string to an int. You should try:
int val = 0;
if (Int32.TryParse(dd.Text, out val))
{
if (val > 31) return;
}
dd.Text > 31
This line wont work. Try:
int.parse(dd.Text) > 31
Also if non numeric characters are entered it wont run, you might want to sanitise first.
What is obvious that You don't think about that what are You doing.
First of all You must to understand what basic types are available in C# and for what re they.
For now You should read about String, and Integer. The You will understand why that code do not work.
If You want to verify, that a text value form a textBox is between two numbers, first of all it need to be number. So You need to cast it...
Then You can operate on it and compare.
String myText = textBox.Text;
int myValue = -1;
if(Int32.tryPart(myText,myValue))
if(myValue > 31)
return;