HELP: Searching for a String in a BinaryTree in Java

Well I got the toString() and inOrder() working, so I know my list is printing correctly. What was making sense in my head obviously wasnt the correct way, and I think Im in that same boat again...(special thanks to hunter9000 for all the help)
In my find method, were supposed to search for a given string, and return the number of compares that it took to find it! For example, if my root was "Brett" and it has children "Bill" and "Tom", then it would take 2 compares to find Tom, three for the next level, etc. If it doesnt find it, then return -1. As for now Im just trying to get it to give my the correct number if it DOES find it!
From looking at the book's find method, I constructed my own...
       public int find(String s)
         Node temp = root;
         int b = 0;
         numberOfCompare++;
         while (temp != null)
            int compare = temp.toString().compareTo(s);
            if (compare < 0)
               temp = temp.getRight();
            else if (compare == 0)
               b = numberOfCompare;
            else
               temp = temp.getLeft();
         return b;
      }Am I doing this all wrong? Because my program gets stuck in an infinite loop I think...

       public int find(String s)
         Node temp = root;
         int b = 0;
         while (temp != null)
            int compare = temp.toString().compareTo(s);
            if (compare == 0)
               b = numberOfCompare;
            else if (compare < 0)
               temp = temp.getRight();
               numberOfCompare++;
            else if (compare > 0)
               temp = temp.getLeft();
        numberOfCompare++;
            else
               b = -1;
         return b;
      }I would think this would work? But its still stuck in the loop!!

Similar Messages

  • How do i search for a string in a txt file using java??

    How do i search for a string in a txt file using java??
    could you please help thanks
    J

    Regular expressinos work just fine, especially when
    searching for patterns. But they seem to be impying
    it's a specific group of characters they're looking
    for, and indexOf() is much faster than a regex.If he's reading from a file, the I/O time will likely swamp any performance hit that regex introduces. I think contains() (or indexOf() if he's not on 5.0 yet) is preferable to regex just because it's simpler. (And in the case of contains(), the name makes for a very clear, direct mapping between your intent and the code that realizes it.)

  • Search for a String within a document (Word, txt, doc) using JSP, JAVA

    Hi
    I have created a little application that uses combination of JSP and HTML. Users of this application can upload documents which are then stored on the server. I need to develop functionality where I can allows users to search for a string within a document. More precisely, user would type in some string in a text box and application will search all uploaded documents for that string and return the downloadable links to those documents that contains that string. I have never done this before. I was wondering if someone could get me started on this or point me to some thread where this idea is already discussed. Any Jave code exists for searching through documents??
    Thanks for your help
    Riz

    http://www.ibm.com/developerworks/java/library/j-text-searching.html
    http://en.wikipedia.org/wiki/Full_text_search
    Type these parameter in yahoo:+efficient text search
    you will need something like openoffice library to read microsoft word document.

  • How can I search for a string like a partial IP address in the global search

    When searching for a string like "10.255." the global search finds messages containing "255" or "10" and both.
    This happens no matter whether quotation is used or not.
    When quotation is used it probably will match on the given order as well, but beeing in the timezone '+0100' the string "10" is always found first (in the email headers...).
    Is there a way to tell the global search not to use '.' or any other character as whitespace?

    When searching for a string like "10.255." the global search finds messages containing "255" or "10" and both.
    This happens no matter whether quotation is used or not.
    When quotation is used it probably will match on the given order as well, but beeing in the timezone '+0100' the string "10" is always found first (in the email headers...).
    Is there a way to tell the global search not to use '.' or any other character as whitespace?

  • How to search for a string in ALL Function Modules source code

    Hello,
    I want to search for the string "HELLO" in all FUNCTION MODULES source code(FM, no reports/programs).
    Is this possible? How?
    Cheers,
    Andy

    hi,
    Execute RPR_ABAP_SOURCE_SCAN to search for a string in the code ... Press where-used-list button on the program which takes to the function group or the function module where it is used ..
    Regards,
    Santosh

  • Searching for a string in an excel file and return true if found.

    How can I search for a string in an excel file and return true if found, its location and also a value.

    The problem with searching an excel file is that it contains a header. It would be easiest if you just read the file into a LabVIEW array and search the array. This way you can also get the index and the value of the location.

  • Search for a String in a list of files

    Could anyone please send me a java sample code which searches for a string from a list of files and returns me the filename and the line in which the Search String was found ?
    Thanks in advance
    RR

    Simple solution would be -
    1. Traverse a directory for each file.
    2. Read each file using Buffered Reader.
    3. Use readLine() method to read a line.
    4. Use String.indexOf to see if the data which you are looking for is there in the line or not.
    5. If its there then store the line number and file name.
    6. When the loop will end you will have list of file name and line number where the data which you are looking for is present.

  • Search for a string in SAP Script

    Hello Experts,
    Is there a way to search for a string in all Z SAP scripts, like ABAP source scan?
    Regards,
    Hari.

    Try using function module "READ_FORM" (you will have to write a simple z-program to find all SAPscripts in your system then use this function module to search the SAPScript Forms for a particular string).
    All you have to do is supply the "FORM" name and it will return all of the Pages, Paragraphs, and Texts etc....
    More specifically, try looping at the "FORM_LINES" internal table result and you will see the SAPScript text there....
    Have fun    !
    Edited by: Christopher Twirbutt on Sep 16, 2009 12:43 AM

  • Is Safari Find function flexible? (Search for inner strings of characters?)

    I'm running 10.6.8 with Safari Version 5.1.7 (6534.57.2). I see that when you search a web page using the Safari Find function, you can only search for the beginnings of words, not for character strings within the words. Is it possible to expand the Find function's capability to search for inner strings of characters?

    use command F or the edit menus to make the page search box visible - click the magnify/arrow icon at the left side of it - choose "contains" or "starts with".

  • Help to search for a string value and return the index in the arraylist

    Hello,
    I just start java programming for the last three weeks and I cannot find a solution for this problem. I have the following List with string and integer value as shown below:
    List<Empl> list= new ArrayList<Empl>();
         list.add(new Empl(1,"Jim", "Balu",88);
         list.add(new Empl(3,"Bob", "Howards",2);
         list.add(new Empl(2,"Chris", "Hup",8);
    I have no problem of sorting this arraylist either by firstname or lastname. However, I cannot think of a way to search for a firstname or lastname and returing the whole row. I do not want to use index since I am asking user to enter the name to search. Here is my code to search for an empl based on index.
    System.out.print("Please enter index to search or (q)uit: ");
              String ans = sc.next();
              System.out.println();
              int ians = Integer(ans);
              if (ans.equalsIgnoreCase("q"))
                        choice = "n";
              else
              System.out.println("index " + list.get(ians)); //this will print out the whole row based on the index
    Since the user will never seen the contents of the arraylist, is there a way that I can search by string last/first name and will get the index location in int if the result is met?
    Please advice and thank you.
    Bob.

    user11191663 wrote:
    Since the user will never seen the contents of the arraylist, is there a way that I can search by string last/first name and will get the index location in int if the result is met?Another possibility is to set up an ArrayList for each thing you want to search on and then every time you add an employee, add the piece of data you want as well, viz:
    Empl e = new Empl(1,"Jim", "Balu",88);
    list.add(e);
    firstNames.add(e.firstName());As long as you always add them in the same order, the indexes will match, so you could do something like
    ians = firstNames.indexOf(nameToFind);to return the index of the name, if it's there (if not, it will return -1).
    I wouldn't recommend this as standard practise, but it should be OK for the level you're at.
    NOTE: indexOf() returns the index of the FIRST matching item. You may want to think about what you want to do if there are more than 1.
    Winston

  • How to: Search for a string in entire movie project?

    I used a copyrighted name a few different places as I was creating a very long and complex game.  I have since removed it from the game where it was previously showing up but when I search the exe, it's still there in a few places.  Is there a way to search the entire movie project and all content, all scripts for a particular string?    For instance "Microsoft".
    If so, I cannot find a way and could use some direction, even if it's an xtra I need to install that adds this capability.
    Thanks!!!!!

    Scripts are easy. You open any script window and hit Ctrl + F and enter your search term in the Find box, ensuring the "All Casts" radio button is checked.
    For text and field members you'll need to write a script that does the search for you. If you were clearer about what you want to happen when you find your search term in a text member then someon could help you with how to perform this. I know there is already code posted to the forum somewhere about how to examine every member of every castLib checking the member type - which would be a very good place to start.

  • Searching for a string in given text file

    Hi,
    I have two strings and i need to search the entire file for the strings and highlight the lines between the strings
    say, for example,
    hi this is xyz
    i am a begineer in java
    can i have some help in this issue please
    i gave 'hi' and 'can' i need the three lines to be highlighted
    can you give me an idea about this.
    how to proceed
    thanks all in advance
    Edited by: anub on Feb 6, 2009 3:24 AM

    Here's an idea. Find a link to the java API. Create a utility class with a method to read a file and a method to write a file. Look in java.io for this. That should keep you busy for a while and give you something specific to ask questions about. Next, create a GUI class and put a button on it. Figure out how to make a button click open a "FileChooser" or "JFileChooser" (Look in the api for that) Imagine that these need to talk to each other so figure out what parameters are needed. After you've done that then figure out how the user is going to enter the two search criteria (something that acts like a text field). Choose a GUI class that supports text highlighting. Display all the information that the user would like to know e.g. The name of the file selected to parse, the name of the file to write, and whether the strings were found successfully.
    kr
    walker

  • Search for a string that contains a '

    I am searching for an email address that contains a ' (o'[email protected]). I think I'd use some sort of ESCAPE character around the tic but I can't seem to get this to work. Appreciate the help.
    select email_addr from customer
    where email_addr = 'o'[email protected]'
    That would be the SQL - should this work?
    select email_addr from customer
    where email_addr = 'o\'[email protected]' ESCAPE ('\'
    This is returning a string not properly terminated error
    Thanks

    A quick search provides this:
    Re: URGENT  update a table with a text that has a single quote in it
    or indeed:
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements003.htm#SQLRF00218
    Message was edited by:
    Boneist

  • Applescript Help: Search for text in Safari DOM tree

    Im trying to make a script really similar what was asked here: Re: Find text in webpage and email notification applescript/automator Except instead of searching the "source code" of the page, I want the script to search the "DOM tree" for the page.
    To summarize, I am trying to make a script that loads a safari page, searches for a particular text in the DOM Tree, and if found will send me an email.
    Here is the code from the other thread I referenced:
    on idle
              set pagURL to "http://page.url.com?whatever"
              if application "Safari" is not running then
                        quit
                        return
              end if
              tell application "Safari"
                        set URL of document 1 of window 1 to "http://your.web.address/"
                        delay 5
      -- delay to let page load.
                        if source of document 1 of window 1 contains "search text" then
                                  my sendAMail()
                        end if
                        return 900 --fifteen minutes
              end tell
    end idle
    on sendAMail()
              tell application "Mail"
                        set theMess to make new outgoing message at end with properties {sender:"your name", subject:"some subject line", content:"The message you want to send to yourself", visible:true}
                        tell theMess
                                   make new to recipient at end of to recipients with properties {address:"[email protected]"}
                        end tell
      -- send theMess
              end tell
    end sendAMail
    Any help would be appreciated!

    For the URL you quote as an example (http://www.sislands.com/coin70/week2/NestedLoops1.htm), using text instead of source worked for me:
    if text of document 1 of window 1 contains "1  2  3  4" then
    another example:
    if text of document 1 of window 1 contains "10 12 14 16" then
    Note a double space between single digits (1  2  3  4) and a single space between double digits (10 12 14 16) is required for a match as per the table format:
    Any full line:
    if text of document 1 of window 1 contains "for (i = 1; i <= 10; i++) { // when i = 10" then
    or partial line works:
    if text of document 1 of window 1 contains "; i++) { // when i = 10" then

  • How to search for particular string in array?

    I am struggling to figure out how to search array contents for a string and then delete the entry from the array if it is found.
    The code for a program that allows the user to enter up to 20 inventory items (tools) is posted below; I apologize in advance for it as I am also not having much success grasping the concept of OOP and I am certain it is does not conform although it all compiles.
    Anyway, if you can provide some assistance as to how to go about searching the array I would be most grateful. Many thanks in advance..
    // ==========================================================
    // Tool class
    // Reads user input from keyboard and writes to text file a list of entered
    // inventory items (tools)
    // ==========================================================
    import java.io.*;
    import java.text.DecimalFormat;
    public class Tool
    private String name;
    private double totalCost;
    int units;
      // int record;
       double price;
    // Constructor for Tool
    public Tool(String toolName, int unitQty, double costPrice)
          name  = toolName;
          units = unitQty;
          price = costPrice;
       public static void main( String args[] ) throws Exception
          String file = "test.txt";
          String input;
          String item;
          String addItem;
          int choice = 0;
          int recordNum = 1;
          int qty;
          double price;
          boolean valid;
          String toolName = "";
          String itemQty = "";
          String itemCost = "";
          DecimalFormat fmt = new DecimalFormat("##0.00");
          // Display menu options
          System.out.println();
          System.out.println(" 1. ENTER item(s) into inventory");
          System.out.println(" 2. DELETE item(s) from inventory");
          System.out.println(" 3. DISPLAY item(s) in inventory");
          System.out.println();
          System.out.println(" 9. QUIT program");
          System.out.println();
          System.out.println("==================================================");
          System.out.println();
          // Declare and initialize keyboard input stream
          BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
          do
             valid = false;
             try
                System.out.print(" Enter an option > ");
                input = stdin.readLine();
                choice = Integer.parseInt(input);
                System.out.println();
                valid = true;
             catch(NumberFormatException exception)
                System.out.println();
                System.out.println(" Only numbers accepted. Try again.");
          while (!valid);
          while (choice != 1 && choice != 2 && choice != 9)
                System.out.println(" Not a valid option. Try again.");
                System.out.print(" Enter an option > ");
                input = stdin.readLine();
                choice = Integer.parseInt(input);
                System.out.println();
          if (choice == 1)
             // Declare and initialize input file
             FileWriter fileName = new FileWriter(file);
             BufferedWriter bufferedWriter = new BufferedWriter(fileName);
             PrintWriter dataFile = new PrintWriter(bufferedWriter);
             do
                addItem="Y";
                   System.out.print(" Enter item #" + recordNum + " name > ");
                   toolName = stdin.readLine();
                   if (toolName.length() > 15)
                      toolName = toolName.substring(0,15); // Convert to uppercase
                   toolName = toolName.toUpperCase();
                   dataFile.print (toolName + "\t");
                   do
                      valid = false;
                      try
                         // Prompt for item quantity
                         System.out.print(" Enter item #" + recordNum + " quantity > ");
                         itemQty = stdin.readLine();
                         // Parse integer as string
                         qty = Integer.parseInt (itemQty);
                         // Write item quantity to data file
                         dataFile.print(itemQty + "\t");
                         valid=true;
                      catch(NumberFormatException exception)
                         // Throw error for all non-integer input
                         System.out.println();
                         System.out.println(" Only whole numbers please. Try again.");
                   while (!valid);
                   do
                      valid = false;
                      try
                         // Prompt for item cost
                         System.out.print(" Enter item #" + recordNum + " cost (A$) > ");
                         itemCost = stdin.readLine();
                         // Parse float as string
                         price = Double.parseDouble(itemCost);
                         // Write item cost to data file
                         dataFile.println(fmt.format(price));
                         valid = true;
                      catch(NumberFormatException exception)
                         // Throw error for all non-number input (integers
                      // allowed)
                         System.out.println();
                         System.out.println(" Only numbers please. Try again.");
                   while (!valid);
                   // Prompt to add another item
                   System.out.println();
                   System.out.print(" Add another item? Y/N > ");
                   addItem = stdin.readLine();
                   while ((!addItem.equalsIgnoreCase("Y")) && (!addItem.equalsIgnoreCase("N")))
                      // Prompt for valid input if not Y or N
                      System.out.println();
                      System.out.println(" Not a valid option. Try again.");
                      System.out.print(" Add another item? Y/N > ");
                      addItem = stdin.readLine();
                      System.out.println();
                   // Increment record number by 1
                   recordNum++;
                   if (addItem.equalsIgnoreCase("N"))
                      System.out.println();
                      System.out.println(" The output file \"" + file + "\" has been saved.");
                      System.out.println();
                      System.out.println(" Quitting program.");
            while (addItem.equalsIgnoreCase("Y"));
    // Close input file
    dataFile.close();
       if (choice == 2)
       try {
          Read user input (array search string)
          Search array
          If match found, remove entry from array
          Confirm "deletion" and display new array contents
       catch block {
    } // class
    // ==========================================================
    // ListToolDetails class
    // Reads a text file into an array and displays contents as an inventory list
    // ==========================================================
    import java.io.*;
    import java.util.StringTokenizer;
    import java.text.DecimalFormat;
    public class ListToolDetails {
       // Declare variable
       private Tool[] toolArray; // Reference to an array of objects of type Tool
       private int toolCount;
       public static void main(String args[]) throws Exception {
          String line, name, file = "test.txt";
          int units, count = 0, record = 1;
          double price, total = 0;
          DecimalFormat fmt = new DecimalFormat("##0.00");
          final int MAX = 20;
          Tool[] items = new Tool[MAX];
          System.out.println("Inventory List");
          System.out.println();
          System.out.println("REC.#" + "\t" + "ITEM" + "\t" + "QTY" + "\t"
                + "PRICE" + "\t" + "TOTAL");
          System.out.println("\t" + "\t" + "\t" + "\t" + "PRICE");
          System.out.println();
          try {
             // Read a tab-delimited text file of inventory items
             FileReader fr = new FileReader(file);
             BufferedReader inFile = new BufferedReader(fr);
             StringTokenizer tokenizer;
             while ((line = inFile.readLine()) != null) {
                tokenizer = new StringTokenizer(line, "\t");
                name = tokenizer.nextToken();
                try {
                   units = Integer.parseInt(tokenizer.nextToken());
                   price = Double.parseDouble(tokenizer.nextToken());
                   items[count++] = new Tool(name, units, price);
                   total = units * price;
                } catch (NumberFormatException exception) {
                   System.out.println("Error in input. Line ignored:");
                   System.out.println(line);
                System.out.print(" " + count + "\t");
                System.out.print(line + "\t");
                System.out.print(fmt.format(total));
                System.out.println();
             inFile.close();
          } catch (FileNotFoundException exception) {
             System.out.println("The file " + file + " was not found.");
          } catch (IOException exception) {
             System.out.println(exception);
          System.out.println();
       //  Unfinished functionality for displaying "error" message if user tries to
       //  add more than 20 tools to inventory
       public void addTool(Tool maxtools) {
          if (toolCount < toolArray.length) {
             toolArray[toolCount] = maxtools;
             toolCount += 1;
          } else {
             System.out.print("Inventory is full. Cannot add new tools.");
       // This should search inventory by string and remove/overwrite matching
       // entry with null
       public Tool getTool(int index) {
          if (index < toolCount) {
             return toolArray[index];
          } else {
             System.out
                   .println("That tool does not exist at this index location.");
             return null;
    }  // classData file contents:
    TOOL 1     1     1.21
    TOOL 2     8     3.85
    TOOL 3     35     6.92

    Ok, so you have an array of Strings. And if the string you are searching for is in the array, you need to remove it from the array.
    Is that right?
    Can you use an ArrayList<String> instead of a String[ ]?
    To find it, you would just do:
    for (String item : myArray){
       if (item.equals(searchString){
          // remove the element. Not trivial for arrays, very easy for ArrayList
    }Heck, with an arraylist you might be able to do the following:
    arrayList.remove(arrayList.indexOf(searchString));[edit]
    the above assumes you are using 1.5
    uses generics and for each loop
    [edit2]
    and kinda won't work it you have to use an array since you will need the array index to be able to remove it. See the previous post for that, then set the value in that array index to null.
    Message was edited by:
    BaltimoreJohn

Maybe you are looking for

  • Poor reflective memory read performanc​e

    I'm having some trouble with the GE 5565 PIORC reflective memory set of VIs for use with our reflective memory setup. I need to copy a pretty sizable chunk of memory out of reflective memory and into a DLL I've written, but the performance on the "GE

  • RoboHelp 9 HTML Memory Error while processing keywords during layout generation

    While I am attempting to generate a project that has never been generated, I am getting the following error when it states processing keywords. I have no other programs open during the generation and am not really sure why I am getting this error. I

  • Embedded Dynamic forms and 2D Barcode.

    The forms that we have developed so far have various dynamic forms embedded which do not work with 2D Barcode.  What alternative designs can we use to achieve similar results? What are design considerations that we should be aware of? We have LC ES 8

  • Streams N way  conflict

    I build two DBs DB1 and DB2 and each has users to connect to it each DB users made insert update delete In insert not problem But in other cases delete and update here is the problem DB1 has updated row what DB1 do to update DB2? It update table wher

  • 2.1.0.62: Bug editing text columns in multiple rows using editor-window

    Hello Forum, I hope this is not a double post, but I did not come up with the right keywords to search for. So here is the bug/strange annoying behavior: When I edit multiple rows of a table using the extra edit-window, it shows the text of the previ