Difference between revisions of "String Binary Search"

From CompSciWiki
Jump to: navigation, search
Line 55: Line 55:
 
String [] ordered = {"a","cake","is","lie","the"};
 
String [] ordered = {"a","cake","is","lie","the"};
  
    print(ordered);
+
print(ordered);
  
 
boolean bool = inOrder(ordered);
 
boolean bool = inOrder(ordered);
Line 61: Line 61:
 
if(bool)
 
if(bool)
 
{
 
{
      System.out.println("This array is ordered.");
+
System.out.println("This array is ordered.");
  
 
while(!done)
 
while(!done)
Line 67: Line 67:
 
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);
+
System.out.println("Guess " +count +": " +input);
  
 
found = findString(input, ordered);
 
found = findString(input, ordered);
Line 130: Line 130:
 
return found;
 
return found;
 
}
 
}
  public static void print(String [] array)
+
public static void print(String [] array)
  {
+
{
    System.out.print("Array: ");
+
System.out.print("Array: ");
  
    for(int i = 0; i < array.length; i++)
+
for(int i = 0; i < array.length; i++)
      System.out.print("\"" +array[i] +"\" ");
+
System.out.print("\"" +array[i] +"\" ");
  
    System.out.println();
+
System.out.println();
  }
+
}
  
 
}
 
}

Revision as of 15:23, 8 April 2010

Back to the Program-A-Day homepage

Problem

You 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

Wiki bench01.jpg


Solution

We shall first start by declaring our variables:

	




Code

Solution Code

Back to the Program-A-Day homepage