'Else statement is not recognized in C# what am I missing?
In C# the program is supposed to count how many valid and invalid values were entered by comparing them to the array and then give a total of the correct and incorrect inputs, but when I enter numbers that are outside of the bounds of the if statement the code from the if statement still runs. I've gone back and reviewed videos and the textbook and I cannot see where my if else statement is lacking.
int[] values = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
int count = 0;
Console.WriteLine("Enter a value between 0 and 10");
foreach (int v in values)
{
Console.ReadLine();
if (values[v] >= 0 || values[v] <= 10)
{
Console.WriteLine("Enter a value");
count++;
}
else
{
Console.WriteLine("Invalid Entry");
count++;
}
}
Console.WriteLine("You entered {0} correct values", count);
Console.WriteLine("You entered {0} incorrect values", count);
Console.ReadKey();
}
}
Solution 1:[1]
(values[v] >= 0 || values[v] <= 10) will always return true, all numbers are either less than 10 or greater than zero. Presumably you want an and (&&) operator to grab values between 0 and 10 inclusive
Also, foreach iterates through the values of an array, not the index, so you don't need to reference values[v], you can just reference v directly (although in your case values[v]==v). Calling values[v] in a foreach runs a huge risk of indexOutOfBounds exceptions. If you want to iterate through the index a straight for loop is more appropriate:
for(int i = 0; i< values.Length; i++)
var myVal = values[i];
Final Edit, you aren't actually checking the user's input
var input = Console.ReadLine();
//you never bothered capturing the user's input with a variable
decimal myNum;
if (decimal.TryParse(input, out myNum)) //did the user give a number?
{
//use myNum instead of values[v]
}
else
{
//process bad input
}
There's a bunch of stuff you can do to make things cleaner, (like removing your array altogether and using for(int i = 0; i< 10; i++) instead, for example), but good code doesn't happen on day 1 (my first few projects make me wanna throw up now), you got this friend.
Solution 2:[2]
You have a foreach loop, you do not need to use
if (values[v] >= 0 || values[v] <= 10)
instead, use
if(v >= 0 || v <= 10)
plus your if statement will always return true because the value you have in your array of int is greater than or equals to 0 or less than or equals to 10.
Try to change the array from
int[] values = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
to
int[] values = { -5, 1, 2, 3, 11, 5, 6, 13, 8, 9, 15, };
and you should have 4 incorrect count, provided you separate the correct count and incorrect count instead of adding them together using the count.
Separate them into validCount and invalidCount
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Loong |
