Vector searching .. ohh my.

This is really not working I'm trying to search a vector which contains 30 elements of 'all strings'.
I'm looking for the following string within a vector.
<Color=5>Except that I don't know what the Color is equal to so I can't use (which would in fact work):
System.out.println ("Found at: " + dataFile.indexOf("<Color=5>")); and ...
System.out.println ("Found at: " + dataFile.indexOf("<Color"));does not work.. it returns '-1'
Any ideas on how I'm to return the line where "<Color=" is located?

Another alternative, which is simpler, if efficiency isn't a major issue:
Create a custom Comparator that will match strings the way you want.
Then, call vector.toArray, sort the list and perform a binary search using your new comparator, using the methods Arrays.sort and Arrays.binarySearch.
Saves you from implementing the iteration and search logic, although there is a much higher overhead.
You could also try various tricks on the comparator to make the sorting and searching faster. For example,
Write a custom Comparator where by you classify Strings into two sets: Those that match the string you're looking for, and those that don't. Those that don't are larger than those that do, and all strings in the same group are "equal".
If you sort using this "ordering," then, if there was a string matching your criteria, it would now be in the fist position of your list. And, as a guess (since I don't know the EXACT algorithm that Arrays.sort uses), I would expect that a quick sort on a list of elements with only two effective values would be very fast (possibly completing in only two passes through the list, if the pivot is placed in the right position).
On the other hand, if you're going to have to search for multiple different strings, but the commonality is that all strings that match are matched based on the beginning of the string, you could sort based on the natural ordering of Strings, and then do the binary search with the new comparator.
Lots of options exist. You just need to find the best one for your purposes. Once again, this method isn't as efficient as searching the list yourself, but it's cleaner, in that, it separates the comparison code (in the Comparator) from the iteration code (in the binary search, or in the sorting). Another alternative with the same effect would be to set up a visitor design, again using a customized comparator. This method, however, requires more effort, as the standard java libraries don't provide a visitor architecture (at least, not that I'm aware of).
It's a shame that the collections class don't already provide a "contains" method that accepts a customized comparator. That sort of thing could be handy in any number of situations. It's also a shame that there doesn't seem to be visitor construct to go with the collections framework. Oh, well. Maybe someday.
- Adam

Similar Messages

  • Do Vectors search and remove in log(n) time?

    Hi,
    I'm working on an application using a Vector to store a sorted list of numbers. Since it's sorted, it would be advantageous to use a log(n) algorithm for searching and removing items. So I'm wondering if the Vector.contains(Object) and Vector.remove(Object) methods know to search for items in a divide-and-conquer manner when it's sorted. I'd use these methods if this is so. Otherwise, I'm wondering if it would make my program run faster if I were to create my own contains(Object) and remove(Object) methods for searching and removing. Does anyone know what kind of algorithms the Vector class uses for these tasks?
    Gib

    Both Vector and ArrayList use an array as an underlying store.
    Thus a remove results in all the subsequent objects being moved up one.
    From the 1.4.2 source for Vector
        public boolean remove(Object o) {
            return removeElement(o);
        public synchronized boolean removeElement(Object obj) {
         modCount++;
         int i = indexOf(obj);
         if (i >= 0) {
             removeElementAt(i);
             return true;
         return false;
        public int indexOf(Object elem) {
         return indexOf(elem, 0);
        public synchronized int indexOf(Object elem, int index) {
         if (elem == null) {
             for (int i = index ; i < elementCount ; i++)
              if (elementData==null)
              return i;
         } else {
         for (int i = index ; i < elementCount ; i++)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    public synchronized void removeElementAt(int index) {
         modCount++;
         if (index >= elementCount) {
         throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                  elementCount);
         else if (index < 0) {
         throw new ArrayIndexOutOfBoundsException(index);
         int j = elementCount - index - 1;
         if (j > 0) {
         System.arraycopy(elementData, index + 1, elementData, index, j);
         elementCount--;
         elementData[elementCount] = null; /* to let gc do its work */
    There is a call to arraycopy to move all the Object down one.

  • Vector Search Errors!!!!!!!

    OK, I know your getting sick of this by now, but I have a new problem, and here it is:
    java.lang.ArithmeticException: / by zero
    I know, its a stupid exception, but the fact is I don't know how in the hell I'm getting it. I've looked over my code and no go. This is where I'm getting it:
            String s;
            int Grade = 0, Passed = 0, NumCourses = 0, Average = 0;
            try {
              for (int j = 0; j < markVec.size(); j++) {
                if (c.equals((String)studentVec.elementAt(i))) {
                  NumCourses++;
                  s = (String)markVec.elementAt(j + 1);
                  Grade = Integer.valueOf(s).intValue();
                  Average = Average + Grade;
                  if (Grade >= 50) {
                    Passed++;
              Average = Average / NumCourses;
              jtfNumStudPassed.setText("" + Passed);
              jtfAverGradeCourse.setText("" + Average);
            catch (Exception x) {
              jtfMessage.setText("Error: " + x);
            }It doesn't seem to be executing the if statement inside the for loop what so ever. I've looked at this for a hour and I couldn't figure it out, can someone help me please.
    Thanks,
    Colin

    Thanks for you code. I used it and I'm still getting the error. I think that the error lies in the fact that it's not going into any of the if statements inside if the for loop. Here's the updated code:
            String s;
            int Grade = 0, Passed = 0, NumCourses = 0, Average = 0;
            try {
              for (int j = 0; j < markVec.size(); j++) {
                if (c.equals((String)studentVec.elementAt(i))) {
                  NumCourses++;
                  s = (String)markVec.elementAt(j + 1);
                  Grade = Integer.valueOf(s).intValue();
                  Average = Average + Grade;
                  if (Grade >= 50) {
                    Passed++;
              Average = Average / NumCourses;
              if(NumCourses != 0){
                Average = Average / NumCourses;
              jtfNumStudPassed.setText("" + Passed);
              jtfAverGradeCourse.setText("" + Average);
            catch (Exception x) {
              jtfMessage.setText("Error: " + x);
            jtfCourseName.setText("" + courseVec.elementAt(i + 1));
            jtfCoordinator.setText("" + courseVec.elementAt(i + 2));
            jtfNumStudPassed.setText("" + Passed);
            jtfAverGradeCourse.setText("" + Average);Plus, the fact that Passed will come out to be zero as well. Any more suggestions, I'm open to any and all suggestions. Thanks any for the code help.
    colin

  • OutOfMemoryError with Vectors

    Hello,
    I am trying to read a lot of data using a database built-in function : search.
    The resultset is put into a vector using the following code :
    public Vector search (......)
    Vector v=new Vector();
    LDAPSearchResults res=ld.search(.......);
    while ( res.hasMoreElements())
    v.addElement((LDAPEntry) results.next());
    return v;
    When calling the method for 30000 registers : Vector v=search(.......)
    I get a OutOfMemorError.
    I have tried to capture the OutOfMemoryError in the search Method
    public Vector search (...)
    try
    } catch (OutOfMemoryError e)
    System.out.println("No memory!!!");
    but it does not work. I still get : java.lang:OutOfMemoryError.
    I am calling those functions from the WEB.
    THanks for helping.

    Hi,
    from my experience catching out OutOfMemoryErrors works in JSP as expected.
    Following Code runs fine on TomCat 3.21: After the Vector eats up all memory there appears the OutOfMemoryError which is caught by the exception handler.
    Could be a problem with you Servlet/JSP container - what are you running? - or the LDAP-Server (?) you are using.
    Whether or not you application can do any sensefull in an out-of-memory-situation is the other side of the coin. ;-)
    Regards
    Martin Schl�ter
    <code>
    <%@page contentType="text/plain"%>
    Plain text JSP
    <%
    String str = " Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt Hallo Welt";
    str += str + str;
    str += str + str;
    str += str + str;
    str += str + str;
    Vector vec = new Vector();
    for(int i = 0; i < Integer.MAX_VALUE; i++)
    try
    vec.addElement(str);
    catch(OutOfMemoryError ex)
    out.println("Ex: " + ex.getClass().getName());
    break;
    if(i % 100000 == 0)
    out.println(i);
    out.flush();
    %>
    </code>

  • How do you search for a partial match in a vector table?

    Hi,
    I have a program that parses some table of mine into a vector table. It has a search function in the program that is intended to search the vector table for a specified keyword that the user enters. If a match is found, it returns true. If no match is found, false is returned.
    That part works great. However, I would like my program to search the vector table to try and find a PARTIAL match of the users entry, instead of looking for a complete match.
    Currently my program uses the Vector method 'contains(Object elem)' to find the complete matches and that part works great. It doesn't seem to work with partial matches. Either the exact syntax of the user's entry is in the table or it isn't.
    Hope I was clear enough. Any thoughts?
    Cheers,
    the sherlock

    You might find this code of interest. It uses the same commands as mentioned previously, but wraps them into a Comparator object. Note that you can't store elements with '*' in the Vector 'v' and that you must sort the elements with Collections.sort() beforehand.
    import java.util.*;
    class WildcardComparator implements Comparator
        public int compare(Object o1, Object o2)
         String string1 = (String)o1;
         String string2 = (String)o2;
         if(string2.indexOf("*") != -1) {
             // take off asterik
             return wildcardCompare(string1,
                           string2.substring(0, string2.length()-1));
         return string1.compareTo(string2);
        public int wildcardCompare(String s1, String key_s) {
         String s1substring = s1.substring(0, key_s.length());
         return s1substring.compareTo(key_s);
    public class wildcard
        public static void main(String[] args)
         Vector v = new Vector();
         v.add("coke");
         v.add("pepsi");
         v.add("7-up");
         v.add("a&w root beer");
         v.add("a&w cream");
         Collections.sort(v, new WildcardComparator());
         String key = "a&w*";
         int index = Collections.binarySearch(v,
                                  key,
                                  new WildcardComparator());
         if(index > 0)
             System.out.println("elem: " + v.get(index));
         else
             System.out.println("item not found");
         key = "c*";
         index = Collections.binarySearch(v,
                                  key,
                                  new WildcardComparator());
         if(index > 0)
             System.out.println("elem: " + v.get(index));
         else
             System.out.println("item not found");
    }

  • Searching for String in Vector

    I know I posted just a few minutes ago about sorting, but I'm making a program (not related to homework at all, this is all for my parents business) and my program needs to store names and fetch them. We have thousands of people in our contacts so it's only logical that I would provide searching so that my mom could easily find a contact she is looking for.
    The contacts are stored in a vector, first name, last name, address, etc. I want to provide a search function that can search the names, or addresss, or both. Then, when a match is found, it returns the results to a JList or something.
    Search Text: "St. Marie"
    Results:
    1. St. Marie, Josh
    2. St. Marie, Someone
    etc etc...

    My program uses files, it uses the files to populate the vector. I'm using a vector, not an array or anything else to access the data in the files. heres a sample of the save method in my program.private void saveContacts ()
          FileOutputStream fos = null;
          try
              fos = new FileOutputStream ("contacts.dat");
              DataOutputStream dos = new DataOutputStream (fos);
              dos.writeInt (contacts.size ());
              for (int i = 0; i < contacts.size (); i++)
                   Contact temp = (Contact) contacts.elementAt (i);
                   dos.writeUTF (temp.fname);
                   dos.writeUTF (temp.lname);
                   dos.writeUTF (temp.phone);
                   dos.writeUTF (temp.fax);
                   dos.writeUTF (temp.email);
          catch (IOException e)
             MsgBox mb = new MsgBox (this, "CM Error",
                                     e.toString ());
             mb.dispose ();
          finally
             if (fos != null)
                 try
                     fos.close ();
                 catch (IOException e) {}
       }The variable "contacts" is my vector.

  • Problem using a vector of strings as patterns to search a text file

    Ideas? Goal is to use several patterns from one file to search for matches in a second file, one pattern at a time. I have added the file of patterns to a vector and created an iterator to grab each pattern successively. I also can effectively search for matches in the second file, but can't seem to find a way to combine them. I've tried nested while(s) in both orders without success.
    Thank you for any suggestions.

    It sounds to me like it should work. What does your search code look like?

  • Searching a Vector of objects

    I'm embarassed to ask this question but I haven't figured out the answer myself yet so I need help.
    I need to be able to search a Vector (it could be an Array just as easily) by only certain parts of the objects in the vector. So for example I have vector v that contains 10 objects o. Objects o are a very small custom class that each have a name and a number. How do I search the vector for the object o that contains name x?
    I tried overriding the equals method of object o and using the IndexOf method of vector v but that did not work.

    I'm embarassed to ask this question but I haven't
    figured out the answer myself yet so I need help.
    I need to be able to search a Vector (it could be an
    Array just as easily) by only certain parts of the
    objects in the vector. So for example I have vector
    v that contains 10 objects o. Objects o are a very
    small custom class that each have a name and a
    number. How do I search the vector for the object o
    that contains name x?Iterate over the Vector and ask each element whether its name is x.
    I tried overriding the equals method of object o and
    using the IndexOf method of vector v but that did not
    work.What does "did not work" mean?

  • Searching through very large vectors

    I am working on a way to process two flat tab delimited files into a tree, assign a x and y coordinate to each node in the tree and output all the nodes (with their coordinates) to a new flat file.
    I currently have a program that works pretty well. It roughly uses the following flow.
    - Read both files into memory (by opening the file reading each line and load the appropriate data from each line into a Vector, making sure no duplicates are entered by comparing the currentline to the last line.
    - Using the first vector (which contains the strating nodes) search through the second vector (which contains parent child relationships between 2 nodes) to construct the tree. For this tree I use a XML DOM Document. In this logic I use a for loop to find all the children for the given node. I store the index of each found reference and when all children are found I loop through all the indexes and delete those records from the parent-child vector.
    - After the tree is created I walk through the tree and assign each node a x and y attribute.
    - When this is done I create a NodeList and use are for-loop to write each node (with x and y) to a StringBuffer which is then written to a file. In this process for each new node that is written I check (in the StringBuffer) if the node (name) is present. If not I write the new Node.
    - For debugging purposes I write all the references from the second Vector to a file and output the XML DOM tree to a XML file.
    This program works wel. It handles files with 10000 start nodes and 20000 parent-child references (30000 nodes in total) in under 2 minutes (using 1:20 for the generation of the output file).
    However when the volume of these file increase it starts to struggle.
    As the ultimate test I ran it with a file that contains 250000 start nodes and 500000 references. For it to run I need to use the -Xmx256m parameter to allocate extra memory. But I ran it for 2 hours and killed it because I didn't want to wait longer.
    What I would like to know is how I can approach this better. Right now I'm loading the data from the files into memory entirely. Maybe this isn't the best approach.
    Also I'm looping through a Vector with 500000 elements, how can this be done more efficiently? However the reference vector isn't sorted in any way.

    Hi,
    That's no problem.. Here's some sample code:
    package tests;
    import java.util.List;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.Iterator;
    class Example {
        private List roots;
        private Map elements;
        public Example() {
            roots = new LinkedList();
            elements = new HashMap();
        public void initRoots(String[] rows) {
            for (int i=0; i<rows.length; i++) {
                String[] parts = rows.split(" ");
    String name = parts[0];
    roots.add(name);
    elements.put(name, new Node(name));
    public void addChilds(String[] rows) {
    for (int i=0; i<rows.length; i++) {
    String[] parts = rows[i].split(" ");
    String parentId = parts[1];
    String name = parts[2];
    addNode(parentId, name);
    private void addNode(String parentId, String name) {
    Node current = (Node)elements.get(name);
    if (current == null) {
    current = new Node(name);
    elements.put(name, current);
    Node parent = (Node)elements.get(parentId);
    if (parent == null) {
    //Parent is missing, is that a problem?. Create it now.
    parent = new Node(parentId);
    elements.put(parentId, parent);
    return;
    parent.addChild(current);
    public void printTree() {
    for (Iterator it = roots.iterator(); it.hasNext(); ) {
    String id = (String)it.next();
    printChildren(id, 1);
    private void printChildren(String id, int depth) {
    Node node = (Node)elements.get(id);
    System.out.println(node);
    private static final class Node {
    private String name;
    private List children;
    private Node(String name) {
    this.name = name;
    children = new LinkedList();
    public void addChild(Node node) {
    children.add(node);
    public String toString() {
    return name + " " + children;
    public static void main(String[] args) throws Exception {
    Example test = new Example();
    test.initRoots(new String[] {
    "SU_1 1 1 1 0 0 0 0",
    "SU_2 1 1 1 0 0 0 0",
    "SU_3 1 1 1 0 0 0 0"
    test.addChilds(new String[] {
    "COM_1 SU_1 PR_1 0 0 0 0 0",
    "COM_1 PR_1 ST_1 0 0 0 0 0",
    "COM_2 SU_2 PR_2 0 0 0 0 0",
    "COM_2 PR_2 ST_2 0 0 0 0 0",
    "COM_3 SU_3 PR_3 0 0 0 0 0",
    "COM_3 PR_3 ST_3 0 0 0 0 0"
    test.printTree();
    The execution prints:
    SU_1 [PR_1 [ST_1 []]]
    SU_2 [PR_2 [ST_2 []]]
    SU_3 [PR_3 [ST_3 []]]
    /Kaj

  • Searching a vector

    Ok, second post. I gave up on the whole array idea and moved to vectors. I got it reading the text file and adding to the vector succesfully. Now I need to search that vector. The text file looks like this:
    9876543 9876543 Y
    0612207 0612207 N
    0123456 0123456 N
    1234567 1234567 Y
    Here's my code so far:
    import java.*;
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class EmailForms extends JFrame implements ActionListener {
         private JTextField jtfUserName;
         private JPasswordField jpfPassword;
         private JButton jbtLogin;
         private JButton jbtCancel;
         Vector LoginData = new Vector();
         public static void main (String[] args) {     
              EmailForms LoginFrame = new EmailForms();
              LoginFrame.setSize(200, 100);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              int screenWidth = screenSize.width;
              int screenHeight = screenSize.height;
              Dimension frameSize = LoginFrame.getSize();
              int x = (screenWidth - frameSize.width)/2;
              int y = (screenHeight - frameSize.height)/2;
              LoginFrame.setLocation(x, y);
              LoginFrame.pack();
              LoginFrame.setVisible(true);     
         public EmailForms () {     
              try {     
                   String UP1Line;
                   FileInputStream fis = new FileInputStream("UP1.txt");
                  BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                  while ((UP1Line = br.readLine()) != null) {
                        StringTokenizer st = new StringTokenizer(UP1Line, " ");
                        while (st.hasMoreTokens()) {
                          LoginData.addElement(st.nextToken());
                    br.close();
                    fis.close();
              catch (IOException ex){
                   JOptionPane.showMessageDialog(this, "Fatal Systems Error", "Email Forms: File Error 1",
                   JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);     
              catch (NullPointerException ex){
                   JOptionPane.showMessageDialog(this, "Fatal Systems Error", "Email Forms: File Error 2",
                   JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);     
              setTitle("E-Forms: Login");
              JPanel jpLoginLabels = new JPanel();
              jpLoginLabels.setLayout(new GridLayout(2, 1));
              jpLoginLabels.add(new JLabel("Username:"));
              jpLoginLabels.add(new JLabel("Password:"));
              JPanel jpLoginText = new JPanel();
              jpLoginText.setLayout(new GridLayout(2, 1));
              jpLoginText.add(jtfUserName = new JTextField(10));
              jpLoginText.add(jpfPassword = new JPasswordField(10));
              JPanel p1 = new JPanel();
              p1.setLayout(new BorderLayout());     
              p1.add(jpLoginLabels, BorderLayout.WEST);
              p1.add(jpLoginText, BorderLayout.CENTER);
              JPanel p2 = new JPanel();
              p2.setLayout(new FlowLayout(FlowLayout.CENTER));     
              p2.add(jbtLogin = new JButton("Login"));
              p2.add(jbtCancel = new JButton("Cancel"));     
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(p1, BorderLayout.CENTER);
              getContentPane().add(p2, BorderLayout.SOUTH);
              jbtLogin.addActionListener(this);
              jbtCancel.addActionListener(this);
         public void actionPerformed(ActionEvent e) {
              String arg = e.getActionCommand();
              int index = find(jtfUserName.getText().trim(), new String(jpfPassword.getPassword()));
              if (arg == "Cancel") {
                   System.exit(0);
                   arg = "";
              if (arg == "Login") {
                   if (index == -1) {
                        JOptionPane.showMessageDialog(this, "Username/Password Not Found", "Email Forms: Login Error",
                        JOptionPane.INFORMATION_MESSAGE);
                   else {
                        if (index == 1 ){
                             JOptionPane.showMessageDialog(this, "Username and Password Found: Admin", "Email Forms: Good",
                             JOptionPane.INFORMATION_MESSAGE);
                        else {
                             JOptionPane.showMessageDialog(this, "Username and Password Found: User", "Email Forms: Good",
                             JOptionPane.INFORMATION_MESSAGE);          
              arg = "";
         public int find(String UName, String PWord) {
              for (int i = 0; i < LoginData.size(); i++) {                                        
                   // if ((first.element.of.first.line.UName  == LoginData.elementAt(i)) && (second.element.of.first.line.PWord == LoginData(i))) {
                   //          if (third.element.of.first.line.yes or no admin == "Y") {
                   //               goto adminside;
                   //               return 1; }
                   //          else {
                   //               goto userside;
                   //               return 2;
              return -1;
    }Essentially this is a login method. The standard username and password. The kicker is the third entry in each line of the vector "Y" or "No". This entry denotes whether or not the user is an admin. If he/she is an admin, they go to an admin program else he/she is a regular user and goes to the user program. I've done some reading on searching vectors in this forum as well as others, but none have I have read have tackled this third entry. Can someone have a look and give me their opinion.
    Thanks in advance,
    Colin

    Here you go:
    1. Use a HashMap to look up credentials.
    2. Use regular expressions to check for certain values
    The code does what you need (just checked it), but you probably wouldn't save the credentials as a "String[]" array. So there's room for improvement ;)
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class EmailForms extends JFrame implements ActionListener {
         private static final long serialVersionUID = -6409081110711705001L;
         private JTextField jtfUserName;
         private JPasswordField jpfPassword;
         private JButton jbtLogin;
         private JButton jbtCancel;
         private HashMap<String, String[]> users;
         public static void main (String[] args) {     
              EmailForms LoginFrame = new EmailForms();
              LoginFrame.setSize(200, 100);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              int screenWidth = screenSize.width;
              int screenHeight = screenSize.height;
              Dimension frameSize = LoginFrame.getSize();
              int x = (screenWidth - frameSize.width)/2;
              int y = (screenHeight - frameSize.height)/2;
              LoginFrame.setLocation(x, y);
              LoginFrame.pack();
              LoginFrame.setVisible(true);     
         public EmailForms () {     
              users = new HashMap<String, String[]>();
              try {     
                   String UP1Line;
                   FileInputStream fis = new FileInputStream("UP1.txt");
                  BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                  while ((UP1Line = br.readLine()) != null) {
                       String [] items = UP1Line.split(" ", 4);     //max. 6 tokens, separated by semicolon
                       users.put(items[0], new String[] { items[1], items[2] });
                       if (items[2].matches("[Yy]"))
                            System.err.println("y");
                       else
                            System.err.println("n");
                    br.close();
                    fis.close();
              catch (IOException ex){
                   JOptionPane.showMessageDialog(this, "Fatal Systems Error", "Email Forms: File Error 1",
                   JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);     
              catch (NullPointerException ex){
                   JOptionPane.showMessageDialog(this, "Fatal Systems Error", "Email Forms: File Error 2",
                   JOptionPane.INFORMATION_MESSAGE);
                   System.exit(0);     
              setTitle("E-Forms: Login");
              JPanel jpLoginLabels = new JPanel();
              jpLoginLabels.setLayout(new GridLayout(2, 1));
              jpLoginLabels.add(new JLabel("Username:"));
              jpLoginLabels.add(new JLabel("Password:"));
              JPanel jpLoginText = new JPanel();
              jpLoginText.setLayout(new GridLayout(2, 1));
              jpLoginText.add(jtfUserName = new JTextField(10));
              jpLoginText.add(jpfPassword = new JPasswordField(10));
              JPanel p1 = new JPanel();
              p1.setLayout(new BorderLayout());     
              p1.add(jpLoginLabels, BorderLayout.WEST);
              p1.add(jpLoginText, BorderLayout.CENTER);
              JPanel p2 = new JPanel();
              p2.setLayout(new FlowLayout(FlowLayout.CENTER));     
              p2.add(jbtLogin = new JButton("Login"));
              p2.add(jbtCancel = new JButton("Cancel"));     
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(p1, BorderLayout.CENTER);
              getContentPane().add(p2, BorderLayout.SOUTH);
              jbtLogin.addActionListener(this);
              jbtCancel.addActionListener(this);
         public void actionPerformed(ActionEvent e) {
              String arg = e.getActionCommand();
              int index = find(jtfUserName.getText().trim(), new String(jpfPassword.getPassword()));
              if (arg == "Cancel") {
                   System.exit(0);
                   arg = "";
              if (arg == "Login") {
                   if (index == -1) {
                        JOptionPane.showMessageDialog(this, "Username/Password Not Found", "Email Forms: Login Error",
                        JOptionPane.INFORMATION_MESSAGE);
                   else {
                        if (index == 1 ){
                             JOptionPane.showMessageDialog(this, "Username and Password Found: Admin", "Email Forms: Good",
                             JOptionPane.INFORMATION_MESSAGE);
                        else {
                             JOptionPane.showMessageDialog(this, "Username and Password Found: User", "Email Forms: Good",
                             JOptionPane.INFORMATION_MESSAGE);          
              arg = "";
         public int find(String UName, String PWord) {
              String [] creds = users.get(UName);
              if (creds!=null && creds[0].matches(PWord)) {
                   System.out.println("ok");
                   if (creds[1].matches("[Yy]"))
                        return 1;
                   else
                        return 0;
              System.err.println("not ok");
              return -1;
    }

  • Urgent pls help!! How to search for an object in vectors?

    Hi,
    I heard that a Vector can store an object right?
    So lets say I created an object called Student that has the attributes: id, name, sex, age
    1) Is vector able to store many students with all these attributes? cos the examples i have seen so far vector only seems to store one attribute
    2) how do i search for sumthin in a vector? let's say i want to key in the student id or his name and find tt student's record to display it?
    thx!

    so sorry... apparantly i didnt copy the last few brackets..
    ===============================================================
    import java.io.*;
    import java.util.*;
    class AddReservation
         static BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
         //Main Method
         public static void main (String[]args)throws IOException
              String custName, comments;
              int covers, date, startTime, endTime;
              int count = 0;
              //User can only add one reservation at a time
              do
                   //Create a new reservation
                   Reservation oneReservation=new Reservation();                         
                   System.out.println("Please enter customer's name:");
                   System.out.flush();
                   custName = stdin.readLine();
                   oneReservation.setcustName(custName);
                   System.out.println("Please enter number of covers:");
                   System.out.flush();
                   covers = Integer.parseInt(stdin.readLine());
                   oneReservation.setCovers(covers);
                   System.out.println("Please enter date:");
                   System.out.flush();
                   date = Integer.parseInt(stdin.readLine());
                   oneReservation.setDate(date);
                   System.out.println("Please enter start time:");
                   System.out.flush();
                   startTime = Integer.parseInt(stdin.readLine());
                   oneReservation.setstartTime(startTime);
                   System.out.println("Please enter end time:");
                   System.out.flush();
                   endTime = Integer.parseInt(stdin.readLine());
                   oneReservation.setendTime(endTime);
                   System.out.println("Please enter comments, if any:");
                   System.out.flush();
                   comments = stdin.readLine();
                   oneReservation.setComments(comments);
                   count++;
              while (count<1);
              class Reservation
              private Reservation oneReservation;
              private String custName, comments;
              private int covers, startTime, endTime, date;
              //Default constructor
              public Reservation()
              public Reservation(String custName, int covers, int date, int startTime, int endTime, String comments)
                   this.custName=custName;
                   this.covers=covers;
                   this.date=date;
                   this.startTime=startTime;
                   this.endTime=endTime;
                   this.comments=comments;
              //Setter methods
              public void setcustName(String custName)
                   this.custName=custName;
              public void setCovers(int covers)
                   this.covers=covers;;
              public void setDate(int date)
                   this.date=date;
              public void setstartTime(int startTime)
                   this.startTime=startTime;
              public void setendTime(int endTime)
                   this.endTime=endTime;
              public void setComments(String comments)
                   this.comments=comments;
              //Getter methods
              public String getcustName()
                   return custName;
              public int getCovers()
                   return covers;
              public int getDate()
                   return date;
              public int getstartTime()
                   return startTime;
              public int getendTime()
                   return endTime;
              public String getComments()
                   return comments;
              //Display the current reservation
              //public void displayReservation()
         //          System.out.println(custName.getcustName());
         //          System.out.println(covers.getCovers());
         //          System.out.println(date.getDate());
         //          System.out.println(startTime.getstartTime());
         //          System.out.println(endTime.getendTime());
         //          System.out.println(comments.getComments());
    ===============================================================
    import java.io.*;
    import java.util.*;
    class searchBooking
         static BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
         public static void main (String[]args)throws IOException
              int choice, date, startTime;
              String custName;
                   //Search Menu
                   System.out.println("Search By: ");
                   System.out.println("1. Date");
                   System.out.println("2. Name of Customer");
                   System.out.println("3. Date & Name of Customer");
                   System.out.println("4. Date & Start time of reservation");
                   System.out.println("5. Date, Name of customer & Start time of reservation");
                   System.out.println("Please make a selection: ");          
                   //User keys in choice
                   System.out.flush();
                   choice = Integer.parseInt(stdin.readLine());
                   if (choice==1)
                        System.out.println("Please key in Date (DDMMYY):");
                        System.out.flush();
                        date = Integer.parseInt(stdin.readLine());
                   else if (choice==2)
                             System.out.println("Please key in Name of Customer:");
                             System.out.flush();
                             custName = stdin.readLine();
                   else if (choice==3)
                             System.out.println("Please key in Date (DDMMYY):");
                             System.out.flush();
                             date = Integer.parseInt(stdin.readLine());
                             System.out.println("Please key in Name of Customer:");
                             System.out.flush();
                             custName = stdin.readLine();
                   else if (choice==4)
                             System.out.println("Please key in Date (DDMMYY):");
                             System.out.flush();
                             date = Integer.parseInt(stdin.readLine());
                             System.out.println("Please key in Start time:");
                             System.out.flush();
                             startTime = Integer.parseInt(stdin.readLine());
                   else if (choice==5)
                             System.out.println("Please key in Date (DDMMYY):");
                             System.out.flush();
                             date = Integer.parseInt(stdin.readLine());
                             System.out.println("Please key in Name of Customer:");
                             System.out.flush();
                             custName = stdin.readLine();
                             System.out.println("Please key in Start time:");
                             System.out.flush();
                             startTime = Integer.parseInt(stdin.readLine());
              public void           
    }

  • Search inside vector?

    help please.
    public class items
      String a;
      int b;
      Vector storageVector = new Vector();
    public void wootwoot();
      items weee = new items();
      a=wootest;
      b=100;
      storageVector.add(weee);
    public void search();
      //How could i search the content of 'string a' inside vector v?
      //In array, i could simply search for array[0].a but it's not compatible with vector.
    }

    _helloWorld_ wrote:
    Loop over the Vector and use elementAt(). Then check the contents using the equals() method.Or just override the equals(Object) method in the items class(and preferably the hashCode() as well) and use Vector's get(Object) to get an item from your Vector.

  • Searching a Vector of SimpleDateFormat objects

    Hi everyone,
    I have implemented a vector of vector structure. Each vector contains a list of objects which have been parserd from a log file. I need to write a method which searches one of the inner vectors containing SimpleDateFormat Objects. Two Dates will be entered by the user and the positons of the date objects found within these two dates needs to be returned. If anyone could help that would be great.
    Jonny

    Hi everyone,
    I have implemented a vector of vector structure. Each
    vector contains a list of objects which have been
    parserd from a log file. I need to write a method
    which searches one of the inner vectors containing
    SimpleDateFormat Objects. Two Dates will be entered
    by the user and the positons of the date objects found
    within these two dates needs to be returned. If
    anyone could help that would be great.
    JonnyWhat? Is it me, or is this a little confused?
    Do the inner vectors really contain instances of java.text.SimpleDateFormat?
    Could you re-state the problem with an example?

  • Search a String Vector for String

    I can't figure out why this won't work. It is supposed to search the id vector for stringValue. It does not return any compilation errors, it just simply won't match stringValue with the id.get(i) method.
            for ( int i = 0; i < id.size(); i++ )
              if ( stringValue == id.get(i) )
                JOptionPane.showMessageDialog( null, "Item already exist.", "Error", JOptionPane.ERROR_MESSAGE );
                stringValue = null;
            }

    "==" tests for object equality (i.e., that two variables contain the exact same object)
    "equals()" tests for object equivalence (i.e., that two objects have the same value, whether or not they are the same object)
    For strings, it's possible to have two different strings to contain the same sequence of characters. In this case, "==" returns false, while "equals()" returns true.

  • Searching Vectors

    If I add several of these objects:
         //A customer
         public PGVideoCust(String first, String last, String address, String address2, String phone, String custID)
              firstName = first;
              lastName = last;
              streetAddress = address;
              cityStateZip = address2;
              phoneNumber = phone;
              ID = custID;
              videosOut.addElement("None");
         } //end customer
    to a vector.. How can i go about searching the vector for ID not just searching for an object in the vector. I tried (vector is customers) customers.indexOf(12432) where 12432 is a valid ID of one of the objects in the vector but it returns -1 everytime.. Understand what I'm trying to do?

    I understand. You need to look at each entry, cast as the object you expect it to be, then test the ID...
    Vector stuff = new Vector(0);
    for(int a = 0; a < stuff.size(); a++){
      // Will throw classCastException if not the right type.
      myObject X = (myObject)stuff.get(a);
      if(X.ID == mySearch){
        // You found it.
    }In similar cases where I know that I'll be storing things based on some known criteria, like an ID, I prefer to use a Hashtable instead. The hashtable stores the goods and all you have to do is ask for the ID like this....
    Hashtable HT = new Hashtable();
    // Store your goodies...
    HT.put(
      myCustomer.ID, // must be an Object so Integer not int
      myCustomer);
    // get the goodies...
    myCustomer = HT.get(theID // Again.  Integer);

Maybe you are looking for