C# Validation for specific input - c#

I'm kinda new to this thread, but in short summary i'm having trouble with a small validation issue. Basically, i'm attempting to make a simple validation program that will collect a user's input and then determine if the input is valid in terms of, input being correctly implemented, the number being positive, and the number having to be either 0, 1, 2, 3, 4 or 5.
The overall program runs, but the issue i'm facing is every form of input is deemed an error, thus displaying my error statement, even if it is a valid input like 5 for example. I feel like there is a small mistake,i have made that is causing this, So is there any suggestions?
int user_input;
int count = 0;
do
{
Console.Write("\n\nUser Input:"
if ((int.TryParse(Console.ReadLine(), out user_input) == false)||(user_input < 0 || user_input != 0 ||user_input != 1 || user_input != 2
|| user_input != 3 || user_input != 4 || user_input != 5))
{
Console.WriteLine("Error : the action entered is not a valid number.");
count = 0;
}
else
count = 1;

Your mistake is because you use OR operator.
For example user print 3. In your statements one condition return false (input != 3), but all others return true.. That's why you always go into if condition..
You can use AND operator, but I can recommend you to simplify your condition. It will be more understandable and readable:
var count = 0;
do
{
Console.Write("\n\nUser Input:");
int user_input;
if ((int.TryParse(Console.ReadLine(), out user_input) == false) || (user_input < 0 || user_input > 5))
{
Console.WriteLine("Error : the action entered is not a valid number.");
count = 0;
}
else
count = 1;
}
while (count != 1);

You already got an answer about the problem with predicate logic. But you can even more simplify with linq like:
var count = (new string[]{"1","2","3","4","5"}).Contains(Console.ReadLine()) ? 1 : 0;

Related

if statement with multiple conditions instead of using AND

I been searching for some information about if statements with multiple conditions but haven't found something that corresponds to myquestion.
I was wondering if you could write:
int n = 3
if (3 < n < 20)
{
//do something..
}
rather than doing:
if (n > 3 && n < 20)
{
//do something..
}
The first statement doesn't work for me which i think it should, because it's plain simple.
Maybe someone can give me the correct syntax for doing so or maybe it's just impossible at all and i just have to go with the AND.
To explain why it's invalid:
if (3 < n < 20)
Could be rewritten as:
if ((3 < n) < 20)
Now 3 < n's outcome would be a bool.
So basically you'll get:
if (true/false < 20)
Which is not valid in C#.
Stefan's answer explains why it's impossible.
But here is a workaround, if you don't want to write that pesky && explicit conditions every time - you can create an extension method:
public static class IComparableExtensions
{
public static bool Between<T>(this T self, T low, T high) where T : IComparable
{
return self.CompareTo(low) > 0 && self.CompareTo(high) < 0;
}
}
And use it like this:
int n = 5;
if(n.Between(3, 20))
{
// do your stuff here
}
Please note, however, that this might be confusing - since Between doesn't specify if the compare is inclusive, exclusive, or inclusive in only one direction - so if you compare, say, 20.Between(10, 20) - should it return true or false?
A better approach would require adding another variable to the method, to indicate that:
[Flags]
public enum CompareMode
{
Exclusive = 0,
IncludeLow = 1,
IncludeHigh = 2,
Inclusive = IncludeLow | IncludeHigh
}
public static class IComparableExtensions
{
public static bool Between<T>(this T self, T low, T high, CompareMode mode) where T : IComparable
{
var compareLow = (mode & CompareMode.IncludeLow) == CompareMode.IncludeLow ? 0 : 1;
var compareHigh = (mode & CompareMode.IncludeHigh) == CompareMode.IncludeHigh ? 0 : -1;
return self.CompareTo(low) >= compareLow && self.CompareTo(high) <= compareHigh;
}
}
Now you use it like this:
if(n.Between(3, 20, CompareMode.Exclusive))
{
// do your stuff here
}
You can see a live demo on rextester.
This way, another person reading this code (or even you, 6 months from now) will know immediately, without having to look inside the Between extension method, if between is inclusive, exclusive, or whatever.
Generally it is not possible what you want to do.
but in your logic if you want to perform single liner logic you can use ternary operator.
for eg. you need to assign value of n to variblae result else it should be 0 as default.
int result = n > 3 ? (n < 20 ? n : 0) : 0
it is equivalent to
int result = 0;
if (n > 3 && n < 20)
{
result = n;
}

Making an int be multiple values?

Is there any way to have a int value that is multiple values?
Under here you can see the code, im doing a minigame as a proof of concept.
currently i have x happen at loop number 4 and y happens at loop number 9.
Is there any way to repeat theese actions on other loops wihout maing it a huge mess like this: i == 4||i == 14 || i == 18
what im trying to ask is if its possible to just write i == a
and then have a be multiple values.
If you havent figured already, im quite the beginner at C#, so if you can explain it in a easy to understand way, i would be very thankfull.
If what i wrote is a bit hard to understand, then im sorry for not being a native english speaker, just ask if you're unsure of what i mean.
for (int i = 0; i < 50; i++)
{
string input;
input = Console.ReadKey().Key.ToString();
Console.Clear();
if (input == "A") Animation.frame1();
else Animation.fall();
if (i == 4) Animation.blocklow2();
if (i == 9) Animation.blockhigh2();
input = Console.ReadKey().Key.ToString();
Console.Clear();
if (input == "W" && i == 4) Animation.blockjump();
if (input == "S" && i == 9) Animation.blockduck();
if (input == "D" && i != 4 && i != 9) Animation.frame2();
else if (input != "W" && i == 4) Animation.fall();
else if (input != "S" && i == 9) Animation.smack();
if (i == 3) Animation.blocklow();
if (i == 8) Animation.blockhigh();
}
You could do if (new int[] { 4, 14, 18 }.Contains(i)) to check for multiple values.
Store a list of ints that you want to check against and then use .Contains
List<int> frame2ints = new List<int>{4,9};
if (input == "D" && !frame2ints.Contains(i)) Animation.frame2();
In certain situations you can perform bitwise tests to see whether some bits are set in your number:
if ((x & 4) != 0)
{
// This case covers numbers
// 4, 5, 6, 7, 12, 13, 14, and many others...
}
General answer to your question is NO, and it only makes sense to use additional knowledge about the values you are testing and then use that knowledge.
Another option is to test whether a number belongs to a sequence, like HHLV said in other answer.
So, how did you get to values 4, 14 and 18?

Code not returning expected number of even and odds

I have a function that takes in a list of numbers and will return how many even numbers and odd numbers there are in the list. However, I passed in a list of numbers but I'm getting 0 results.
Here is my function -
public static string HowManyEvenAndOdds(List<int> numbers)
{
int numOfOdds = 0;
int numOfEvens = 0;
int numOfBoth = 0;
foreach (int i in numbers) {
bool isEven = i % 2 == 0;
bool isOdd = i % 3 == 0;
numOfBoth = isEven && isOdd ? numOfBoth++ : numOfBoth;
numOfEvens = isEven ? numOfEvens++ : numOfEvens;
numOfOdds = isOdd ? numOfOdds++ : numOfOdds;
}
return string.Format("This list has {0} odd numbers,\n{1} even numbers,\nand {2} numbers that are even and odd.", numOfOdds, numOfEvens, numOfBoth);
}
Any ideas on what I'm doing wrong here? I debugged through it but none of the lists are incrementing.
Thanks
your are not calculating odd in the correct way
i%3 does not catch 5 which is also an odd number, try this instead
bool isEven = i % 2 == 0;
bool isOdd =!isEven;
I agree with Schachaf Gortler's answer as well as p.s.w.g's comment. Just do:
foreach (var number in numbers)
{
// A number is even if, and only if, it's evenly divisible by 2
if (number % 2 == 0)
numEvens++;
// A number is odd if, and only if, it's NOT evenly divisible by 2
// Alternatively, a number is odd if it isn't even and vice versa
else
numOdds++;
}
As p.s.w.g. mentioned, there's no such thing as a number that's both even and odd, so eliminate that completely.
Incidentally, numOfEvens++ retrieves the value and then increments it, which is why your code didn't work.
I think you should have a look at your test for isOdd
Use the Linq Count extension.
int numOfOdds = numbers.Count(x => x % 2 != 0);
int numOfEvens = numbers.Count(x => x % 2 == 0);
Of course you don't need to evaluate both expressions, as per the comment below.

C#: Choosing operator depending on boolean value (in one line)

I'm trying to get away with a slick one liner as I feel it is probably possible.
I'll put my code below and then try to explain a little more what I'm trying to achieve.
for (int p = 0; p < 2; p++)
{
foreach (string player in players[p])
{
if (PlayerSkills[player].streak_count *>* 0) //This line
PlayerSkills[player].streak_count++;
else
PlayerSkills[player].streak_count = 0;
}
}
*(p==0 ? >:<) the comparison operator is chosen depending on p.
Of course what I've written is rubbish. But basically I want to use >0 when p==0, and <0 when p>>0. Is there a nice way to achieve this?
Well, you should use what is most readable, even if it is not as consice. That said...
// Invert the count for all but the first player and check for a positive number
if (PlayerSkills[player].streak_count * (p==0 ? 1 : -1) > 0)
I don't know about slick, but the following and/or combination is one line:
if ((p == 0 && PlayerSkills[player].streak_count > 0)
|| PlayerSkills[player].streak_count < 0)
...
This will only ever do the array index once (due to the p==0 condition occurring first) and so is equivalent to the "ternary" you wrote (albeit a bit more verbose).
p > 0 ? whenGreaterThanZero : whenZeroOrLess ;
E.g.
int p = 1; bool test = p > 0 ? true : false ;
Lets test = True

c# do while ( Two condition )

im trying to do a loop when either one of the two conditions are met for ten times..
This involves a box of bottles either Sugar or Salt where the person must pick randomly two bottles. He/She will stop picking when it was choosen 10 times... It doesnt seem to work.
int sugar = 0;
int salt = 0;
do
bottle1.choose
bottle2.choose
{
if ((bottle1 = 'Sugar') && (bottle2 = 'Sugar'))
{
Console.Write("Sugar");
Sugar++;
}
else if (bottle1 = 'Salt') && bottle1 = 'Salt')
{
Salt++;
Console.Write("Salt");
}
else
{
Console.Write("None");
}
}
while ((Salt < 10) || Sugar < 10);
Currently you'll keep looping while either of them have been chosen 10 times. I suspect you want:
while (Salt < 10 && Sugar < 10)
Having said that, the code you've given is clearly pseudo-code anyway - it wouldn't compile for various reasons. If you could post a short but complete program demonstrating the problem, we could give an answer with more confidence. Likewise, saying "It doesn't seem to work" is akin to going to the doctor and expecting a diagnosis from "I'm not feeling well." More details please...
You declare salt and suger at the start here, but inside the loop you use Salt and Sugar. Are they properties you have defined somewhere else? Are you sure they do what you expect them to? Have you tried using the variables inside the loop instead of the properties, so your code looks like this?
int sugar = 0;
int salt = 0;
do
bottle1.choose
bottle2.choose
{
if ((bottle1 = 'Sugar') && (bottle2 = 'Sugar'))
{
Console.Write("Sugar");
sugar++;
}
else if (bottle1 = 'Salt') && bottle1 = 'Salt')
{
salt++;
Console.Write("Salt");
}
else
{
Console.Write("None");
}
}
while ((salt < 10) || sugar < 10);
Your parentheses are uneven on your if and while statements, your variable names mismatch, your bottle.choose statements must also be under the do-while loop, and you're using an assignment operator = on your conditions:
int sugar = 0;
int salt = 0;
do {
bottle1.choose();
bottle2.choose();
if ((bottle1 == 'Sugar') && (bottle2 == 'Sugar'))
{
Console.Write("Sugar");
sugar++;
}
else if ((bottle1 == 'Salt') && (bottle1 == 'Salt'))
{
salt++;
Console.Write("Salt");
}
else
{
Console.Write("None");
}
} while ((salt < 10) || (sugar < 10));
I can't tell from your question if you want to stop if EITHER salt or sugar has been chosen, or if you want to stop when 10 total items have been chosen.
If you're looking for the former, then Jon Skeet's answer will do it for you.
If you're looking for the latter, then I think you're looking for the following:
while (Salt + Sugar < 10);
If I understand the code correctly, both bottles must be of the same taste to do the increment.
First error seem to be the test condition for the "Salt", you check twice for the "bottle1", test should be :
else if (bottle1 = 'Salt') && bottle2 = 'Salt')
Your Variables names are mismatching, again you may take the condition for selection of both salt and sugar in the "while statement" itself.

Categories