Comparing elements inside a vector

Hello,
I am having a hard time understanding how to compare elements inside a vector. I have a vector of six strings and I want to compare the first element at index 0 with all other elements at positions 1-5. After that, compare the element at position 1 with elements at positions 2-5 and so on until all elements have been compared against each other.
Can some one please advise me on how to achieve this?
Thank you.

joor_empire wrote:
Thanks for replying. I tried using nested loops, but I keep getting array index out of bound error.Hmmm, then you're doing it wrong.
For more information, you'll have to give us more info, such as your code (please use code tags when posting it though).

Similar Messages

  • Display elements inside a vector

    How do I display the elements inside a vector and place it inside a TextArea in a JFrame?
    //start of Itm class
    public class Itm
         private String name;
         private int qty;
         private double price;
         public int SetQty (int nQty)
              qty = 0;
              if (nQty>0)
                   qty = nQty ;
              return qty;
         public String SetName (String strName)
              name = "";
              name = strName;
              return name;
         public double SetPrice (String name)
              if (name == "6pcs. Chckn McNggts")
                   price = 57;
              else if (name == "HB")
                   price = 25;
              else if (name == "Big Mac Meal")
                   price = 115;
              else if (name == "CHB Meal")
                   price = 115;
              else if (name == "RICE")
                   price = 11;
              else if (name == "1pc. Chicken Mcdo w/rice")
                   price = 57;
              else if (name == "CHB")
                   price = 35;
              else if (name == "1pc. Chicken w/Sphtti")
                   price = 90;
              else if (name == "BMD Meal")
                   price = 50;
              else if (name == "GRAVY")
                   price = 8;
              else if (name == "Mc Spghtti")
                   price = 35;
              else if (name == "DCHB")
                   price = 69;
              else if (name == "1pc. Chickn Mcdo Happy Ml")
                   price = 92;
              else if (name == "Mc Spghtti Happy Ml")
                   price = 76;
              else if (name == "X-SAUCE")
                   price = 8;
              else if (name == "Mc Rice Brgr Beef Sprme")
                   price = 75;
              else if (name == "Qrtr Pounder w/cheese")
                   price = 85;
              else if (name == "Mc Flurry")
                   price = 30;
              else if (name == "Sundae Cup")
                   price = 25;
              else if (name == "X-MAYO")
                   price = 8;
              else if (name == "Mc Rice Brgr Chckn Sprme")
                   price = 85;
              else if (name == "Big Mac")
                   price = 85;
              else if (name == "PIE")
                   price = 20;
              else if (name == "Sundae Cone - Vanilla")
                   price = 12;
              else if (name == "ICE MIX")
                   price = 25;
              else if (name == "Crispy Chicken Fillet")
                   price = 35;
              else if (name == "Reg Fries")
                   price = 25;
              else if (name == "Mc Float")
                   price = 25;
              else if (name == "Mc Float w/LFries")
                   price = 55;
              else if (name == "Ornge Juice")
                   price = 26;
              else if (name == "Brgr Mcdo")
                   price = 25;
              else if (name == "Lrge Fries")
                   price = 36;
              else if (name == "Softdrink")
                   price = 19;
              else if (name == "Icd Tea")
                   price = 26;
              else if (name == "Coffee")
                   price = 27;
              return price;
    //end of Itm class
    //start of Receipt class
    import java.util.*;
    public class Receipt
         Vector vReceipt = new Vector();
         Itm i = new Itm();
         public void addItem (Itm i)
              vReceipt.addElement(i);
    //end of Receipt class

    http://forum.java.sun.com/thread.jspa?threadID=5225026&tstart=0
    Thanks for double posting butthole!
    NO HELP FOR YOU

  • Compare element in a vector

    hi,
    I want to compare the float no in a vector e.g. [{0.2},{0.55}];
    but I cannot just compare the 2 using x.elementAt(i) becoz this return object so
    i do ix.elementAt(i) nstanceOf float but it pops up error,
    but I am actually doing object instance of float, I am wondering where it was wrong
    for(int i=1;i<x.size(); i++){
    if(x.elementAt(i) instanceOf float){
    if( x.elementAt(i)< x.elementAt(i-1)){
    mean_dist.addElement(x.elementAt(i));
    mean_dist.toString();
    System.out.println("train data: "+ mean_dist);
    anyone can give me idea
    many thx

    yep, sure thing, when you use Vector.elementAt(index) it returns an Object, not a Float
    but... you KNOW its a Float cos thats what you put there! ok?
    Vector has to return Object as when the class was written there was no idea what you would use it for and Object is the general class that coveres just about everything..
    what you need to do is "cast" to Float, that is saying,
    "ok you dont know its a Float, but I do ( I hope) and I want you to deal with it as a Float"
    the way you do this is Float gimme=(Float)myVector.elementAt(index);this tell the compiler that you expect a Float and should deal with the return as a Float
    the compiler will do its best to use what it gets as a Float, but if it cant (ie if you put something that isnt a Float in myVector at (index)) then it will generate a ClassCastException
    you dont HAVE to catch this, but you may if you want

  • Comparing elements in vector..

    hi ,
    how to compare elements in 2 vectors(diff size)
    pls help
    arvin

    thks for your help,
    for(int i=0;i<=v.size();i++)
    if(v.elementAt(i).equals(v2.elementAt(i))
    }when i did like this iam getting error
    arvin

  • Sort element inside JComboBox

    Hi,
    i have a JComboBox containing list of Strings
    so lets say:
    String[] test = {"omega", "alpha", "beta", "Arc"}
    JComboBox testing = new JComboBox(test);
    now is there a way to sort the elements inside the JComboBox once they have been inserted ? or anyone know how to sort the elements before putting them in inside JComboBox ?
    the sample code was just for testing and I am dealing with MANY elements (at least 10) inside the JComboBox
    thanks in advance
    if you have any links that helps with this topic, I will also appreciate it

    <hmm>
    1) Check out the [url http://java.sun.com/docs/books/tutorial/collections/index.html]Collections API
    2) Note that using a java.util.Vector, (which combo box accepts in its constructor), allows you to do
    one of two things:
    ............If you are using a custom object, have it implement Comparable
    ............If you are using flat Strings, never mind...
    Then calling java.util.Collections.sort(myVector) would do this for you. NOTE: by not implementing
    Comparable, this may have undesirable results....
    A number of collection objects sort by default when you add an element.....

  • Can not find individual element in the Vector

    Hi everyone,
    I have employeeRecord class .
    I have employee Vector.
    I have created two employeeRecord and added them to my employee Vector.
    I am trying to test my employee Vector by using lgName = "rez704" .
    However I do not see any result.
    I was expecting the for loop to go through my employee Vector and
    find the login name which matches with my test variable lgName.
    ANy clues?
    many thanks
    Vector  employeeVector = new Vector();
    Enumeration e = empVector.elements();
      String nameLog = "rea700";
      String fName   = "ameri";
      String passW   = "765";
      employeeRecord  emp = new employeeRecord(nameLog, fName, passW);
      empolyeeVector.addElement(emp);
      String nameLog2 = "rez704";
      String fName2   = "Xamre";
      String passW2   = "kv281"
      employeeRecord  emp = new employeeRecord(nameLog2, fName2, passW2);
      empolyeeVector.addElement(emp);
      String lgName = "rez704";
      int i = 0;
      for(Enumeration e1 = employeeVector.elements() ; e1.hasMoreElements() ;)
                if (lgName.equals(empVector.elementAt(i)))
                   System.out.println("Login Name Found");
             e1.nextElement();
          }

    Hi everyone,
    I have employeeRecord class .
    I have employee Vector.
    I have created two employeeRecord and added them to
    my employee Vector.
    I am trying to test my employee Vector by using
    lgName = "rez704" .
    However I do not see any result.
    I was expecting the for loop to go through my
    employee Vector and
    find the login name which matches with my test
    variable lgName.
    ANy clues?
    many thanks
    Vector  employeeVector = new Vector();
    Enumeration e = empVector.elements();
    String nameLog = "rea700";
    String fName   = "ameri";
    String passW   = "765";
    employeeRecord  emp = new employeeRecord(nameLog,
    g, fName, passW);
    empolyeeVector.addElement(emp);
    String nameLog2 = "rez704";
    String fName2   = "Xamre";
    String passW2   = "kv281"
    employeeRecord  emp = new employeeRecord(nameLog2,
    2, fName2, passW2);
    empolyeeVector.addElement(emp);
    String lgName = "rez704";
    int i = 0;
    for(Enumeration e1 = employeeVector.elements() ;
    ; e1.hasMoreElements() ;)
    if
    if (lgName.equals(empVector.elementAt(i)))
    System.out.println("Login Name
    tln("Login Name Found");
    e1.nextElement();
    Hi Guys,
    No, none of the solution works!!
    I tired the following just for testing.
    int l = 0;
    if ( empVector.elementAt(l).equals(e1.nextElement()) )
    <
    <
    <
    it only prints the first employee record
    Login Name Found
    login Name = reza700
    Last name = ameri
    passWord = 765
    in my original question which I had posted, I wanted to compare not the whole Vector object but
    only to access loginName whithin the emplyoeeVector and comapare it
    with the lgName which is used as testing.
    But the example which I had uesed above and it the wrong type of example the wole emplyoee record is found in the emplyoee vector.
    any help is appreciated.
    thank you again

  • Sorting a vector where each element is a vector

    Hi,
    Sorry for the post but I can't seem to get my head around sorting in Java using Comparator.
    I've a vector where each element is a vector containing strings, integers and doubles and the first element of each vector is a double.
    I need to sort the vector based on this first value of each element which is a vector.
    Hope some can help,
    Thanks in advance,
    Lou

    Here is a generic comparator you can use to sort a List. Vector implements the List interface to you can sort the Vector.
    import java.util.Comparator;
    import java.util.List;
    * A comparator to sort Lists of data based on a column within each List
    public class ListComparator implements Comparator
        private int column;
        private boolean ascending;
        ListComparator(int column, boolean ascending)
            this.column = column;
            this.ascending = ascending;
        public int compare(Object a, Object b)
            List v1 = (List)a;
            List v2 = (List)b;
            Object o1 = v1.get(column);
            Object o2 = v2.get(column);
            // Treat empty strings like nulls
            if (o1 instanceof String && ((String)o1).length() == 0)
                o1 = null;
            if (o2 instanceof String && ((String)o2).length() == 0)
                o2 = null;
            // Sort nulls so they appear last, regardless  of sort order
            if (o1 == null && o2 == null) return 0;
            if (o1 == null) return 1;
            if (o2 == null) return -1;
            //  Compare objects
            if (o1 instanceof Comparable)
                if (ascending)
                    return ((Comparable)o1).compareTo(o2);
                else
                    return ((Comparable)o2).compareTo(o1);
            else  // Compare as a String
                if (ascending)
                    return o1.toString().compareTo(o2.toString());
                else
                     return o2.toString().compareTo(o1.toString());
    }You invoke the sort by using:
    Collections.sort(yourVector, new ListComparator(column, ascending));

  • How to find all query elements inside a Query

    Hi,
    I would like to find out all query elements inside my query.
    Is there any table which stores all query elements inside my query ?
    Thanks
    Pratyush

    Hi,
    Query elements are stored in this  follwing table:
    SE11
    Table name : RSZELTXREF [Directory of query element references]
    other query related tables :
    Tables used in  Queries
    RSZELTDIR      Directory of the reporting component elements
    RSZELTTXT    Texts of reporting component elements 
    RSZELTXREF  Directory of query element references 
    RSRREPDIR     Directory of all reports (Query GENUNIID) 
    RSZCOMPDIR  Directory of reporting components 
    RSZRANGE    Selection specification for an element 
    RSZSELECT    Selection properties of an element
    RSZELTDIR     Directory of the reporting component elements 
    RSZCOMPIC    Assignment reuseable component <-> InfoCube
    RSZELTPRIO   Priorities with element collisions
    RSZELTPROP  Element properties (settings)
    RSZELTATTR  Attribute selection per dimension element 
    RSZCALC        Definition of a formula element 
    RSZCEL           Query Designer: Directory of Cells
    RSZGLOBV     Global Variables in Reporting
    RSZCHANGES  Change history of reporting components 
    Hope it will helps you.
    Thanks
    Hemav

  • How to associate lines in a text file as an elements of the Vector?

    Hi!
    I have used BufferedReader(new FileReader(c:/java/MyText.txt)) to read from MyText.txt file. Now I know how to load content of this file (every line in file describes each photo in my photo-set) into a Vector. But how to associate lines of MyText.txt as an elements of the Vector?
    Thanks Felipe for his help.
    DM.

    Thank you telism,
    Let me tell you the whole story.
    I'm trying to write an application which has to show my image files (set of photos) with a text description. The list of image files placed into the JList. So, when I select a file from the JList it shows me an image (everything is OK).
    But, every image has it's text description in MyText.text file. It's a file with each text line for every image. Actually, I am trying to connect two actions - showing my image and setting it's specified text line description (from MyText.txt) in a JTextArea. I thought that the best way to do this with my text it is like I did it with my images through Vector. But No Success.
    Can You help me on that? If You will show me how to do it on my example I will really appreciate it.
    Thank You DM.
    Here is my application:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class UnitA extends JPanel implements ListSelectionListener {
    BasicUnitA Myapplet;
    JPanel listPanel, picturePanel;
    Vector imageNames1;
    JList list1;
    JLabel picture1;
    JScrollPane listScrollPane1, pictureScrollPane1, TSP1;
    JTextArea TA1;
    int index;
    UnitA (BasicUnitA parent, boolean p1, boolean p2) {
    Myapplet=parent;
    //Read image names from a properties file
    ResourceBundle imageResource1;
    try{
    imageResource1 = ResourceBundle.getBundle("imagenames1");
    String imageNamesString1 = imageResource1.getString("images");
    imageNames1 = parseList(imageNamesString1);
    } catch (MissingResourceException e) {
    System.err.println("Please, add properties file with image names.");
    System.exit(1);
    //Create one list of images and put it in a scroll pane and panel
    list1 = new JList(imageNames1);
    list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list1.setSelectedIndex(0);
    list1.addListSelectionListener(this);
    listScrollPane1 = new JScrollPane(list1);
    listScrollPane1.setPreferredSize(new Dimension (120,120));
    //Set up the picture label and put it in a scroll pane
    ImageIcon firstImage1 = new ImageIcon("java/Applications/images/fotos/" +
    (String)imageNames1.firstElement());
    picture1 = new JLabel(firstImage1);
    picture1.setPreferredSize(new Dimension (firstImage1.getIconWidth(),
    firstImage1.getIconHeight()));
    pictureScrollPane1 = new JScrollPane(picture1);
    pictureScrollPane1.setPreferredSize(new Dimension (500,360));
    pictureScrollPane1.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createCompoundBorder(
    BorderFactory.createLoweredBevelBorder(),
    BorderFactory.createEmptyBorder(5,5,5,5)),
    BorderFactory.createLineBorder(Color.black)));
    pictureScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLL
    BAR_ALWAYS);
    TA1 = new JTextArea();
    TA1.setLineWrap(true);
    TA1.setWrapStyleWord(true);
    TA1.setEditable(false);
    TA1.setFont(new Font("Serif", Font.PLAIN, 16));
    TSP1 = new JScrollPane(TA1);
    TSP1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_
    ALWAYS);
    TSP1.setPreferredSize(new Dimension(500,40));
    TSP1.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createCompoundBorder(
    BorderFactory.createLoweredBevelBorder(),
    BorderFactory.createEmptyBorder(5,5,5,5)),
    BorderFactory.createLineBorder(Color.black)));
    public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) return;
    JList theList1 = (JList)e.getSource();
    if (theList1.isSelectionEmpty()) {
    picture1.setIcon(null);
    TA1.setText(null);
    } else {
    index = theList1.getSelectedIndex();
    ImageIcon newImage1 = new
    ImageIcon("java/Applications/images/fotos/" +
    (String)imageNames1.elementAt(index));
    picture1.setIcon(newImage1);
    picture1.setPreferredSize(new Dimension (newImage1.getIconWidth(),
    newImage1.getIconHeight()));
    picture1.revalidate();
    try{
    BufferedReader reader = new
    BufferedReader(new FileReader("c:/java/Applications/MyText.txt")));
    String str;
    while((str = reader.readLine()) != null) {
    TA1.setText(TA1.getText()+str);
    reader.close();
    }catch(IOException evt){};
    protected static Vector parseList(String theStringList) {
    Vector v = new Vector(10);
    StringTokenizer tokenizer = new StringTokenizer (theStringList, " ");
    while (tokenizer.hasMoreTokens()) {
    String image = tokenizer.nextToken();
    v.addElement(image);
    return v;

  • Which interface would you use to list each element of a vector?

    Which interface would you use to list each element of a vector?

    The laugh's on you, twit! Nobody takes kindly to lazy bums trying to cheat on their homework nor exams. Take a hike loser!

  • Number of elements inside an XML node?

    If myXML.person.length() gives me the number of person nodes
    in my XML file, then how do I count the number of elements inside
    each person node if each one has a different name (such as address,
    zip, etc.)?

    //returns the number of elements in the first person node
    trace(myXML.person[0].elements().length());

  • How  to set focus on an element inside a datatable on load

    How to set focus on an element inside a datatable on load

    Check out https://blogs.oracle.com/groundside/entry/ever_wondered_how_uncommitteddatawarning_works and
    Decompiling ADF Binaries: Checking for dirty data
    Timo

  • Access elements inside a dialog box/window using applescripts

    Am new to applescript. I want to access elements inside a dialog box/window. I tried following code.
    tell application "System Events" set procs to processes set windowName to {} repeat with proc in procs try if exists (window 1 of proc) then repeat with w in windows of proc if w's name contains "App Name" then copy w's name to the end of windowName copy properties of w to the end of windowName end if end repeat end if end try -- ignore errors end repeat end tell return windowName
    But am only able to get the 4 elements from window: 1.Close 2.Minimize 3.Maximize 4.window title
    Nothing from inside the window/dilog.
    Can any one help me with this pls?

    Hi,
    Like this :
    tell application "System Events"
          tell process "App Name"
                tell (first window) to if exists then return UI elements
          end tell
    end tell

  • Set a container element inside class to exit a loop

    Hi,
    I want to set a container element inside a class to exit a loop.
    The element is marked as import/export parameter and the binding from the task to the container exists as well.
    The loop has a condition  &finish& = X but I cannot exit the loop. Looks like the value gets never updated in the container.
    When i am using a container operation to set the element its working but i want to do this out of my method in the class.
    Is it not possible to change a container element inside a loop without using a container operation?
    Thanks,
    Christoph

    Hi,
    Using the container operation is a good method to solve the problem. But if you intend to do that in the method coding itself then you will have to have it as the export parameter of the method. You can view all the import and export parameters of a method by going to the Business Object Builder (SWO1) and then choose the method and click on the "Parameters" Button. Once you are done with the interface of the method use that method in the workflow builder as a task and in the binding there are two rows. One for the import that occurs just below the container elements and the export parameters appear below the import in a separate window. Make sure you have the binding set there too as this is where you can transfer the container elements back to the workflow container from the task container and it should work. Maybe you are missing that in the binding.
    Hope it helps,
    Sudhi

  • Kill a thread and remove the element from the vector

    Hi All
    I have attached each Vector element to a thread which I later want to kill and remove that element from the Vector.
    Thread.join(milliseconds) allows this functionality to let the thread die after n milliseconds.
    However, I want to delete this element from the Vector now.
    Can someone please throw some light on this?
    Here the code I have written for this:
    try
         System.out.println(counter);
         int xCoord = generator.irand(25,200);     // X-coord of AP
         int yCoord = generator.irand(25,200);     // Y coord of AP
         listMN.addElement(new MobileNode((int)mnId,new Point2D.Double(xCoord,yCoord)));
         listMNcoords.addElement(new Point2D.Double(xCoord,yCoord));
         for(int i=0;i<vnuBS.returnBSList().size();i++)
              if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=3)&&(vnuBS.returnBSList().get(i).getChannelCounter()>0))
                   double c = exponential() * 10000;
                   long timeToService = (long)c;
                   System.out.println("BS "+vnuBS.returnBSList().get(i).id+" is connected to MN ");
                   vnuBS.returnBSList().get(i).reduceChannelCounter();
                   System.out.println("Channel Counter Value Now: "+vnuBS.returnBSList().get(i).getChannelCounter());
                   mobileNodesThread.addElement(new Thread(listMN.elementAt(mobileNodeCounter)));
                   mobileNodesThread.elementAt(mobileNodeCounter).setName(mobileNodeCounter+"");
                   mobileNodesThread.elementAt(mobileNodeCounter).start();
                   mobileNodesThread.elementAt(mobileNodeCounter).join(100);
    //                              System.out.println("Died");// thread dies after join(t) milliseconds.
                   System.out.println("ListMN getting generated : " + mobileNodesThread.get(mobileNodeCounter));
              else if(vnuBS.returnBSListCoords().get(i).contains(xCoord,yCoord)&&(vnuBS.returnBSList().get(i).getChannelCounter()<=0))
                   listMN.remove(this.listMN.lastElement());                         //dropcall
                   System.out.println("Removed "+mnId);
                   removeCounter++;
                   mnId = mnId--;
                   mobileNodeCounter--;
              mnId = mnId+1;
         Thanks a lot.

    I'm not sure if what you are trying to accomplish is correctly implemented.
    The method join does not kill the thread. It will wait for the specified time for the thread to exit. If you want the thread to run for a specified ammount of time, develop the run method of that thread with that in mind. Do not try to kill it from the outside, but let it terminate itself (gracefull termination).
    Now for your question regarding the vector (you should probably be using ArrayList nowadays): I would implement the observer pattern for this job. Make the threads post an event on the interface when they are done, let the main thread register itself with the threads and synchronize the method that handles the events. In that method you can remove the object from your list.
    I'm not sure if you want to use thread anyhow, could you tell us what it is that you are trying to accomplish?

Maybe you are looking for

  • PDF attachment in mail, can not open, getting black screen all time

    I am checking my gmail account in firefox and when there is PDF attachmant with mail and I click on same PDF documents I am not able to see that documents and my firefox get hang for some time and I remove that tab and again it works fine When I try

  • "Grab" has stopped working!

    My "Grab" has suddenly started to produce a "Jazzy" Pattern made up of a small piece of the original screen repeated hundreds of times! I have downloaded a couple of other Screenshot applications but the same thing happens! Any ideas? EMAC 1.2ghz g4

  • MSI GX640 VBIOS for Win7 64-bit?

    Hey all, first-time poster here. Also I apologize in advance if this is the wrong forum, but I wasn't really sure where to post this so I just followed the placement of similar threads I've found. Anyway, I've had my MSI GX640 for about a year now an

  • Printing Issue ... Width

    Here's my code ,what's happening , is when i try to print and the page is too wide , instead of cutting the line and goto next one , it SHRINK the font to have it fit .. Here's the code .. let me know what im doing wrong... public int print(Graphics

  • Reverse Engineering and Mocha...

    I've heard of a program called Mocha that can take a .class file and spit out the source code and a program named Crema that can prevent this. Now, if this is the case, java is useless for encryption based programs or anything else that might be prop