why does the BinarySearch() method return a negative value that isn't "-1" and why is this if statement not accepting "m" as being valid?

  • Thread starter Thread starter Mikestriken
  • Start date Start date
M

Mikestriken

Guest
Hey people!

I was getting an error in the past where the BinarySearch() method was returning a negative number like "-4" and I was wondering if anyone can explain the criteria required for that to happen.

Lastly here is the current problem:

I have the following declared:

string[] sizes = new string[4] {"M", "L", "S", "X" };
double[] prices = new double[4] {8.99, 12.5, 6.99, 15 };
string input = null;
string size;
double price = 0;
bool valid = false;
bool truth = false;


and here is the if statement:


// there should be a do here
input = Console.ReadLine().ToUpper();
Console.WriteLine();
if (Array.BinarySearch(sizes, input) <= -1 || int.TryParse(input, out int num))
Console.Write("Please enter a valid letter ");
else
truth = true;
// "while (truth == false);"

int test = Array.BinarySearch(sizes, input);

size = input;



So when I place "m" into the input, the if statement says that it's not a valid letter.

and I have placed a watch on the "test" variable to see what the BinarySearch() method returns and it shows a "0" as it should.


So why am I being errored?

Continue reading...
 
Back
Top