static void PrintPartOfArray(int[] array, int from, int to)
{
int x = array.Length;
if (from > x && from < 0)
{
Console.WriteLine("there is an exeption!");
}
if (to > x && to < 0)
{
Console.WriteLine("there is an exeption!");
}
else
{
for (int i = from; i <= to; i++)
{
Console.WriteLine(array[i]);
}
}
}
static void Main(string[] args)
{
int[] array2 = new int[] { 3, 6, 54, 24, -90, 7, 4 };
PrintPartOfArray(array2,2,7);
}
it supposes to show the "exception error when the function receives a number outside the length of the array, for some reason it not working, when I checked with the debugger it simply skipped the if loops, what have I done wrong?
If from
and to
are greater than x
, they can't possibly also be less than 0. Recall that x
is the length of an array, which can't be negative. That being said, it's literally impossible for either of your if
statements to evaluate to true
. Did you mean ||
instead?
Also, the last index of the array is array.Length - 1
, not array.Length
. Similarly, the first item in the array is at index 0
, not index 1
. I think that your array indices are off by 1 here.
Consider "early return" for things like this.
if (from > array.Length - 1 || to > array.Length - 1 || from < 0 || to < 0)
{
Console.WriteLine("One of your arguments is out of range.");
return;
}
// Normal, error-free code goes here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.