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

Similar Messages

  • 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

  • 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.

  • How to search for a string in a DefaultListModel

    I have a list of names stored in a DefaultListModel and would like to know how i can search for a particular name
    i assume i would have to use the method below but not sure of how to implement it
    so basically i would have a texfield where a user can type in a name to find in the list
    public int indexOf(Object elem)
    Searches for the first occurence of the given argument.
    Parameters:
    elem - an object.
    or i might be wrong
    Any ideas of how to write this mechanism
    Can anyone please help on this

    The DefaultListModel uses a Collection of some sort (Vector at present) to store data. You can get this data in two ways:
       DefaultListModel model = (DefaultListModel)list.getModel();
        Enumeration e = model.elements();
        while(e.hasMoreElements()) {
          if (e.nextElement().equals(elem)) return;
        }or
        Object[] array = model.toArray();
        for (int i = 0; i < array.length; i++) {
          if (array.equals(elem)) return;

  • How to search for exact string?

    Is there any way to search for the text string exactly as I enter it? Like 'exact search' in the OSS notes?
    For example, I'm trying to find the forum posts regarding the Excel 2007 file format XLSX. By XLSX the search finds hundreds of entries, but most of them are not even close. For example, this was one of the top results: /thread/1078918 [original link is broken]
    Why is it getting picked up when 'xlsx' doesn't even appear there? We are frequently complaining about the users who don't use search before posting, but, frankly, if it works like this, I can't blame them...

    >
    Jelena Perfiljeva wrote:
    > Why is it getting picked up
    >
    => https://forums.sdn.sap.com/search.jspa?threadID=&q=%22Whyisitgettingpicked+up%22&objID=f40&dateRange=all&numResults=15&rankBy=10001
    "Why is it getting picked up"
    I regularly use this to (re)find threads where I remembered a specific comment or even spelling mistake.
    Perhaps a better option in your case would be to use an AND between individual terms.
    I generally tend to edit the search string parameters directly, as it seems to cache previous results and do a search within a search. That might be an option for you as well though.
    Cheers,
    Julius
    Edited by: Julius Bussche on Jul 10, 2009 11:38 PM

  • How to search for a string

    Hi All,
    My requirement is to search string Like "List Price",if the input field is having this string at any place i need to transfer input value to target.
    Could any one help me on this writing a UDF for this.
    Input : Final List Price Vendor
    check for :List Price
    then pass the other values to Target.
    Thanks,
    Madhu

    Hi,
    Check with this UDF
    public String Search(String a,String b,Container container)
    String c;
    int i;
    i = a.indexOf(b);
    if(i == -1)
       c = " ";
    else
       c = a;
    return c;
    Here a is the input and b is the search string.
    0r
    if the value of search string doesnt change dynamically then the UDF can be like this
    public String Search(String a,Container container)
    String c;
    String b;
    b = "List price"
    int i;
    i = a.indexOf(b);
    if(i == -1)
       c = " ";
    else
       c = a;
    return c;
    Edited by: malini balasubramaniam on Aug 5, 2008 9:15 AM

  • How to search a particular string in whole schema?

    Hi Everyone,
    My DB version is
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bi
    PL/SQL Release 10.2.0.1.0 - Production
    "CORE 10.2.0.1.0 Production"
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    Suppose I have a column say "EMAIL_ID" in employee table. The employee name is "abcd" and his email_id is "[email protected]".
    The column name is changing from "EMAIL_ID" to "EMAIL_ADDRESS" due to poor naming convention standard.
    Now I've only one constant value i.e. "[email protected]"...So is there any way if I will write a query with this value and I'll get the list of
    tables and the exact column name where this mail_id exists?
    Regards,
    BS2012.

    create or replace
    PROCEDURE value_search_db(p_string VARCHAR2,p_datatype VARCHAR2)
    IS
    S SYS_REFCURSOR;
    CURSOR c_user_col IS
    SELECT TABLE_NAME,COLUMN_NAME,DATA_TYPE FROM USER_TAB_COLUMNS,TAB
    WHERE TABLE_NAME=TNAME AND TABTYPE='TABLE'
    ORDER BY TABLE_NAME;
    TYPE TAB_LIST
    IS
      RECORD
        TABLE_NAME VARCHAR2(1000),
        COLUMN_NAME     VARCHAR2(1000),
        DATA_TYPE    VARCHAR2(100));
    TYPE T_TAB_LIST
    IS
      TABLE OF TAB_LIST;
      L_TAB_LIST T_TAB_LIST := T_TAB_LIST();
      L_STMT CLOB;
      l_exists NUMBER;
    BEGIN
    FOR i IN c_user_col LOOP
      L_TAB_LIST.EXTEND;
      L_TAB_LIST(L_TAB_LIST.LAST).TABLE_NAME := I.TABLE_NAME;
      L_TAB_LIST(L_TAB_LIST.LAST).COLUMN_NAME     := i.COLUMN_NAME;
      L_TAB_LIST(L_TAB_LIST.LAST).DATA_TYPE     := i.DATA_TYPE; 
    END LOOP;
    FOR i in 1..L_TAB_LIST.COUNT LOOP
        l_exists := NULL;
        IF L_TAB_LIST(I).DATA_TYPE = p_datatype THEN
          L_STMT := 'SELECT 1 FROM '||L_TAB_LIST(I).TABLE_NAME||' WHERE '
                      ||L_TAB_LIST(I).COLUMN_NAME||' LIKE ''%'||p_string||'%''';
          OPEN S FOR L_STMT;
          FETCH S INTO l_exists;
          CLOSE S;
          IF l_exists IS NULL THEN
          NULL;
          ELSE
            DBMS_OUTPUT.PUT_LINE('Table name: '||L_TAB_LIST(I).TABLE_NAME||'--Column Name: '||L_TAB_LIST(I).COLUMN_NAME);
            DBMS_OUTPUT.PUT_LINE(L_STMT);
          END IF;
        END IF;
    END LOOP;
    END value_search_db;
    I t may help you.:-)

  • How to search for a particular word in a string?

    How to search for a particular word in a string?
    thanks for your help....

    This works fine.
    public class Foo {
        public static void main(String[] args) {
        String s = "Now is the time for all good...";
        String s2 = "the time";
        System.out.println(s.contains(s2));
        System.out.println(s.contains("for al"));
        System.out.println(s.contains("not here"));
    }output:true
    true
    falseYou must have something else wrong in your code.
    JJ

  • How to search for a particular pattern in a string

    Hi,

    Hi ,
    How to search for a particular pattern in a string?
    I heard about java.util.regex; and used it in my jsp program.
    Program I used:
    <% page import="java.util.regex"%>
    <% boolean b=Pattern.matches("hello world","hello");
    out.println(b);%>
    I run this program using netbeans and am getting the following error message.
    "Cannot find the symbol : class regex"
    "Cannot find the symbol : variable Pattern "
    How to correct the error?

  • 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.)

  • How to search for a particular word in a long document?

    How to search for a particular word in a long document?

    What program are you using to read the document?
    Good luck.

  • How to search for upper/lower case using string using JAVA!!!?

    -I am trying to write a program that will examine each letter in the string and count how many time the upper-case letter 'E' appears, and how many times the lower-case letter 'e' appears.
    -I also have to use a JOptionPane.showMessageDialog() to tell the user how many upper and lower case e's were in the string.
    -This will be repeated until the user types the word "Stop". 
    please help if you can
    what i have so far:
    [code]
    public class Project0 {
    public static void main(String[] args) {
      String[] uppercase = {'E'};
      String[] lowercase = {'e'};
      String isOrIsNot, inputWord;
      while (true) {
       // This line asks the user for input by popping out a single window
       // with text input
       inputWord = JOptionPane.showInputDialog(null, "Please enter a sentence");
       if ( inputWord.equals("stop") )
        System.exit(0);
       // if the inputWord is contained within uppercase or
       // lowercase return true
       if (wordIsThere(inputWord, lowercase))
        isOrIsNot = "Number of lower case e's: ";
       if (wordIsThere(inputword, uppercase))
         isOrIsNot = "number of upper case e's: ";
       // Output to a JOptionPane window whether the word is on the list or not
       JOptionPane.showMessageDialog(null, "The word " + inputWord + " " + isOrIsNot + " on the list.");
    } //main
    public static boolean wordIsThere(String findMe, String[] theList) {
      for (int i=0; i<theList.length; ++i) {
       if (findMe.equals(theList[i])) return true;
      return false;
    } // wordIsThere
    } // class Lab4Program1
    [/code]

    So what is your question? Do you get any errors? If so, post them. What doesn't work?
    And crossposted: how to search for upper/lower case using string using JAVA!!!?

  • When I am searching for any particular song or album from my shared ITUNES folder, the search is conducted  in the apple store and not on the shared library. How to search for the song in the shared library

    I am using IPAD Mini.When I am searching for any particular song or album from my shared ITUNES folder, the search is conducted  in the apple store and not on the shared library. How to search for the song in the shared library

    Search for shared library is impossible, as far as I know.  Searches supported - are local and internet.

  • How to search for perticular substring in given string.

    Hi, Can any one tell me how to search for perticular substring in given string.
    example:
    I have to search for CA in given Order type it may be CA10 or CA15. Please Do the needful.

    Hi Aniruddha,
    check this...
    Data var string,
    var = 'India'.
    search var for 'Ind'.
    if sy-subrc = 0.    " var having ind
    Message 'Ind found' type 'I'.
    else  .            "var not having ind
    Message 'Ind not Found' type 'I'.
    endif.
    thanx
    bgan.

  • 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?

Maybe you are looking for