This program has to finds whether a book dealer carries a requested book. When using BinarySearch() method both argument inside the parenthesis should be in integer.
How to convert string array ("books") into integer array.
using System;
public class DebugSix04
{
public static void Main()
{
String[] books = { "Rich Dad", "Poor Dad", "Catch-22", "Harry Potter", "Programming Using C#", "Wizard of Oz", "The Deep" };
Console.Write("What book are you looking for? ");
int enterBookName = Convert.ToInt32(Console.ReadLine());
int x = Array.BinarySearch(books, enterBookName);
if (x > 0)
Console.WriteLine("{0} not found", enterBookName);
else
Console.WriteLine("Yes, we carry {0}", enterBookName);
}
}
Loading
VulpesPosted Feb 22, 2012, 11:35 AM
Also the array needs to be sorted first before this method can be used.
So I think you can do it like this - I've made the search case insensitive which would be normal when looking for book titles:
Posted Feb 23, 2012, 9:53 AM
VulpesPosted Feb 23, 2012, 9:30 AM
I've altered the code so that the compiler will now choose the Array.BinarySearch
Notice that it's not necessary to specify the generic type parameter
using System;
Posted Feb 23, 2012, 8:24 AM
Could you explain what is meant by "This is necessary because it's a static method of the Array class".
This program has been altered to take two different types in BinarySearch() method. Please use T[] and correct it.
using System;
namespace BinarySearchDemo
{
class Program
{
static void Main(string[] args)
{
int[] zip = new int[5] { 1000, 2000, 3000, 4000, 5000 };
Console.Write("Entre a ZIP code ");
string enter = Console.ReadLine();
int num = Array.BinarySearch(zip, enter);
if (num < 0)
Console.WriteLine("Zip is not found");
else
Console.WriteLine("Array position is {0}", num);
Console.ReadKey();
}
}
}
VulpesPosted Feb 23, 2012, 5:07 AM
Posted Feb 22, 2012, 5:36 PM
VulpesPosted Feb 22, 2012, 2:30 PM
http://msdn.microsoft.com/en-us/library/system.array.binarysearch.aspx
As you'll see, there isn't one which takes an int as its first parameter.
In fact all of them take the array itself as the first parameter. This is necessary because it's a static method of the Array class.
The first and second parameters are always of different types.
Posted Feb 22, 2012, 12:11 PM
I wish to know whether both arguments inside the parenthesis of BinarySearch() method can be different types. That means for example:
BinarySearch(int, string)