I am writing a program for school and need some help, i am supposed to create a method in which will find an int and tell me how many times it took to find it...
I have three methods in this one big method... One for a String, one for a Double, and one for an Int... The trouble is there is a part where i start an if statement and compare an int to a String using the greater than symbol (>) and it is giving me the incompatible types error, which makes sense, because i am comparing an int to a string...
here is the code
The second if statement in the while loop is giving me trouble. so as you can see i tried doing item>list[mid].length so that it compares the length, but its still giving me an error... I cant figure out how to compare the two so that the if statement will work... Im sure there is some extremely simple way of doing this and im an idiot and missing itCode:public static boolean BinarySearch(String list[], int item) { boolean found=false; int lo = 0; int hi = list.length -1; int counter = 0; while(lo<=hi && !found) { counter++; int mid = (lo + hi) / 2; if(list[mid].equals(item)) { found = true; } else { if(item > list[mid].length) lo = mid +1; else hi = mid -1; } } System.out.print("Number of searches:"+counter+" "); return found; }but please tell me it....
-git
change it to list[mid].length()
in String class length is a function
Method names are always starting with lower case:
Code:binarySearch(String list[], int item)What's that? You are comparing String to an Integer. That will always return "false".Code:if(list[mid].equals(item))
To convert a String to an integer:
Then you can go ahead and compare them, since they are both the same data type.Code:String myString = "42"; int myInt = Integer.parseInt(myString);
Last edited by curse; 03-05-2010 at 10:35 PM.
Thanks everyone! i got it running, i am using it as a method to call into a sorting int program later...
/thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks