Difference between revisions of "String Binary Search"
Line 54: | Line 54: | ||
String [] notOrdered = {"the","cake","is","a","lie"}; | String [] notOrdered = {"the","cake","is","a","lie"}; | ||
String [] ordered = {"a","cake","is","lie","the"}; | String [] ordered = {"a","cake","is","lie","the"}; | ||
+ | |||
+ | print(ordered); | ||
boolean bool = inOrder(ordered); | boolean bool = inOrder(ordered); | ||
Line 59: | Line 61: | ||
if(bool) | if(bool) | ||
{ | { | ||
+ | System.out.println("This array is ordered."); | ||
+ | |||
while(!done) | while(!done) | ||
{ | { | ||
input = JOptionPane.showInputDialog("Enter the word you are looking for?",null); | input = JOptionPane.showInputDialog("Enter the word you are looking for?",null); | ||
count++; | count++; | ||
+ | System.out.println("Guess " +count +": " +input); | ||
found = findString(input, ordered); | found = findString(input, ordered); | ||
Line 125: | Line 130: | ||
return found; | return found; | ||
} | } | ||
+ | public static void print(String [] array) | ||
+ | { | ||
+ | System.out.print("Array: "); | ||
+ | |||
+ | for(int i = 0; i < array.length; i++) | ||
+ | System.out.print("\"" +array[i] +"\" "); | ||
+ | |||
+ | System.out.println(); | ||
+ | } | ||
} | } | ||
+ | |||
Revision as of 15:21, 8 April 2010
Back to the Program-A-Day homepage
ProblemYou are given an ordered array of Strings. Your program will do a few things. First, it must verify that the array is indeed ordered. This will be done in a separate method, and the mothod will return a boolean value. ('true' indicating that the array is ordered) Second, if the array is ordered, then you must prompt the user to guess a word that might be in the array. This prompt will be done with JOptionPane. Another method will then be required to conduct a binary search of the array to look for the user's guess. This method will also return a boolean indicating success or failure. Finally, the user will only be allowed to guess a maximum of five times before the program will stop. For output, the program will first print the array. Then it will print the status of the array. (whether it is ordered or not) Then it will print out every guess the user makes. Finally, print out the user's number of attempts and whether they succeeded in entering a word that's in the array. Your output should look something like this: Array: "word1" "word2" "word3" It is ordered. Guess 1: blah Guess 2: blah Guess 3: word1 The array contains "word1". It took you 3 attempt(s) to get it. |
Problem Solving and Programming Examples
| |
---|---|---|
SolutionWe shall first start by declaring our variables:
| ||
Code |