Sorting a 2D Vector

Suppose i have a vector like...
V = [['A',2.0],['X', '4.0'],['Y',5.0].......]
How do i sort this vector based on value i.e I want to sort it based on value of each string..so my result should be V = [[Y,5.0],[X,4.0],[A,2.0]] or something like that...Precisly,I want a way so that i can do it in minimum number of steps or takes ;least code to do it...

Implement a custom java.util.Comparator that works on the type of objects stored in the Vector and use that with java.util.Collections.sort().

Similar Messages

  • How to sort a object vector by its integer item ?

    hi everybody,
    [there were few topics on this in the forum, but nothing could solve my problem yet. so, please instruct me]
    I have to sort a vector which contains objects, where each object represents, different data types of values,
    ex: {obj1, obj2, obj3, ....}
    obj1---->{String name, int ID, String[] departments}
    i have to sort this vector at three times, once by name, then by ID and then by departments.
    Leaving name and department , first i want to sort the ID of each object and then re-arrange the order of objects in the array according to new order.
    what i did was, copied the vector all objects' ID values to an integer array then i sorted it using selection sort. but now i want to re-arrange the vector, but i still can't. please guide.
    here is the sort i did, and the
    int[] ID = new int[mintomaxID.size()];
              for(int i=0;i<mintomaxID.size();i++)
                   ObjectStore_initialData obj_id = (ObjectStore_initialData)mintomaxID.elementAt(i);
                   ID[i] = obj_id.getID();
              System.out.println("Before sorting array");
              for(int i=0;i<ID.length;i++)
                   System.out.println(ID);     
              System.out.println();
              int i, j, m, mi;
    for (i = 0; i < ID.length - 1; i++) {
    /* find the minimum */
    mi = i;
    for (j = i+1; j < ID.length; j++) {
    if (ID[j] < ID[mi]) {
    mi = j;
    m = ID[mi];
    /* move elements to the right */
    for (j = mi; j > i; j--) {
    ID[j] = ID[j-1];
    ID[i] = m;
    System.out.println("After sorting array");
    for(int y=0;y<ID.length;y++)
                   System.out.println(ID[y]);     
    //*****here is where i need to re-arrange the entire vector by ID.
    I do understand this is some sort of database sort type of a question. but there's no database. it's simply i just want to sort the vector.
    Thank you.

    hi camickr,
    thank you for the detailed reply. but i still don't understand somethings. i tried to read the API and look for the collections.
    i have ObjectStore_initialData class (similar to person class), so do i still have to do a comparable class out of this class ? please simplify that.
    public class ObjectStore_initialData
         String NAME;
         int ID;
         String[] DPART;     
         public ObjectStore_initialData(String name, int id, String[] departments)
              NAME=name;
              ID=id;
              DPART = departments;
    public String getName()//----
              return NAME;
    public String getID()//----
              return ID;
    public String getDpart()//----
              return DPART;
    /*next class is the interface to collect the values from the user and put all of them at once in a vector*/
    //this class is to sort the vector by ID
    public class sorter
       public sorter()
       public static void sortbyID(Vector mintomaxID)
             int[] ID = new int[mintomaxID.size()];
              for(int i=0;i<mintomaxID.size();i++)
                   ObjectStore_initialData obj_id = (ObjectStore_initialData)mintomaxID.elementAt(i);
                   ID[i] = obj_id.getID();
              System.out.println("Before sorting array");
              for(int i=0;i<ID.length;i++)
                   System.out.println(ID);     
              System.out.println();
              int i, j, m, mi;
    for (i = 0; i >< ID.length - 1; i++) {
    /* find the minimum */
    mi = i;
    for (j = i+1; j < ID.length; j++) {
    if (ID[j] < ID[mi]) {
    mi = j;
    m = ID[mi];
    /* move elements to the right */
    for (j = mi; j > i; j--) {
    ID[j] = ID[j-1];
    ID[i] = m;
    System.out.println("After sorting array");
    for(int y=0;y<ID.length;y++)
                   System.out.println(ID[y]);     
    //*****here is where i need to re-arrange the entire vector by ID.
    /*new comparable class */
    public class ObjectStore_initialData implements Comparable
         String NAME;
         int ID;
         String[] DPART;     
         public ObjectStore_initialData(String name, int id, String[] departments)
              NAME=name;
              ID=id;
              DPART = departments;
    public String getName()//----
              return NAME;
    public String getID()//----
              return ID;
    public String getDpart()//----
              return DPART;
    static class IDComparator implements Comparator
              public int compare(Object o1, Object o2)
                   ObjectStore_initialData p1 = (ObjectStore_initialData )o1;
                   ObjectStore_initialData p2 = (ObjectStore_initialData )o2;
                   return p1.getID() - p2.getID();
    /*how can i put the vector here to sort? */
    public sorter()
    public static void sortbyID(Vector mintomaxID)
    int[] ID = new int[mintomaxID.size()];
              for(int i=0;i<mintomaxID.size();i++)
                   ObjectStore_initialData obj_id = (ObjectStore_initialData)mintomaxID.elementAt(i);
                   ID[i] = obj_id.getID();
              System.out.println("Before sorting array");
              for(int i=0;i<ID.length;i++)
                   System.out.println(ID[i]);     
              System.out.println();
              int i, j, m, mi;
    for (i = 0; i >< ID.length - 1; i++) {
    /* find the minimum */
    mi = i;
    for (j = i+1; j < ID.length; j++) {
    if (ID[j] < ID[mi]) {
    mi = j;
    m = ID[mi];
    /* move elements to the right */
    for (j = mi; j > i; j--) {
    ID[j] = ID[j-1];
    ID[i] = m;
    System.out.println("After sorting array");
    for(int y=0;y<ID.length;y++)
                   System.out.println(ID[y]);     
    /* using collections to sort*/
    Collections.sort(mintomaxID, new IDComparator());
    and to check the new order i wanted to print the vector to command line.
    still it doesn't do anything.
    the url you mentioned is good as i see. but how can i implement that in my class ? please instruct and simplify. i know i just repeated the code, i didn't understand to do a comparable class in collections for this class. Please explain where i'm head to and where's my misleading point here.
    Thank you.
    Message was edited by:
    ArchiEnger.711

  • Need to sort two vectors at the same time! please help!

    I have
    vectorA: 2 4 9 1 7 6 8
    vectorB: two four nine one seven six eight
    i want to sort these two vectors in parallel
    what is the best way?
    i could just do Collection.sort(vectorA) and get
    1 2 4 6 7 8 9
    but i want the vectorB to have a corresponding order
    please help!!
    thanks

    public class Pair implements Comparable {
    private int value;
    private String name;
    public int getValue() {
    return this.value;
    public void setValue(int value) {
    this.value = value;
    public String getName() {
    return this.name;
    public void setName(String name) {
    this.name = name;
    public int compareTo(Object o) {
    Pair that = (Pair) o;
    return this.value - that.value;
    place both in a Collection (vector is a bad choice if you are going to do sorting LinkedList is better) the Collections.sort method will sort
    according to the compareTo method.

  • Vector sorting

    i save data on vector :
    while (st.hasMoreTokens())
              searchWord=st.nextToken();
         vector.addElement(searchWord);     
    vector={a,y,h,k,...,}
    then i calculate the occuerency of each words and save them in the second vector
    v2={1,9,2,5}
    i want to sort the 2 vector based on v2 " the number of occuerency for each word the result should be like :
    v1={y,k,h,a}
    v2={9,5,2,1}
    i did try to use for loop but unfortunately string.equals() or compareTo()doesn't work although i convert object to string
    any suggestions
    thanks

    Storing occurence and word in two diferent vectors (!) is yucky to begin with.
    Have an Occurance class. Make it implement Comparable using the counter variable. Then use Collections.sort() to sort the list of Occurence objects.

  • Sorting three vectors simultaneously

    I have total of 3 independent vectors (vecStudent, vecMarks and vecChoice). All three are in conjuction with each other i.e. the 0th element of all the 3 vectors correspond to a record of a single student.
    The initial elements are as :-
    vecStudent vecMarks vecChoice
    ABC 9.6 1
    XYZ 9.4 3
    ABC 9.6 2
    XYZ 9.4 2
    LMN 9.4 1
    XYZ 9.4 1
    XYZ 9.4 4
    etc....
    The desired result after sorting is :- (sort vecMarks first, then vecStudent and then vecChoice)
    vecStudent vecMarks vecChoice
    ABC 9.6 1
    ABC 9.6 2
    LMN 9.4 1
    XYZ 9.4 1
    XYZ 9.4 2
    XYZ 9.4 3
    XYZ 9.4 4
    During the swapping process of elements of any vector, the elements of the other two vectors also have to be swapped to maintain the record intact. In the bubble sort algorithm written by me, the result obtained is:-
    vecStudent vecMarks vecChoice
    ABC 9.6 1
    ABC 9.6 3
    ABC 9.6 2
    LMN 9.4 1
    XYZ 9.4 2
    XYZ 9.4 1
    XYZ 9.4 4
    XYZ 9.4 3
    i.e. the vecChoice vector is not getting sorted properly in-spite of including it in the swapping condition.
    Can anyone suggest the code using 'Quick sort' algorithm to sort the above vectors?
    The sorting code(using bubble sort) written is as:-
    String tmp;
    boolean con1, con2, con3;
    tcnt=0;
    for (int i=0; i<=cnt-1; i++) {
    for (int j=0; j<=i; j++) {
    // check marks
    con1 = Float.parseFloat((String)marks.elementAt(j)) < Float.parseFloat((String)marks.elementAt(i));
    // check if the student no. is same, marks are same and if choice no. is less
    con2 = (Integer.parseInt((String)stud.elementAt(j)) == Integer.parseInt((String)stud.elementAt(i)) && Float.parseFloat((String)marks.elementAt(j)) == Float.parseFloat((String)marks.elementAt(i)) && Integer.parseInt((String)choice.elementAt(j)) < Integer.parseInt((String)choice.elementAt(i)));
    // check if the marks are same but the student no. is less
    con3 = (Float.parseFloat((String)marks.elementAt(j)) == Float.parseFloat((String)marks.elementAt(i)) && Integer.parseInt((String)stud.elementAt(j)) < Integer.parseInt((String)stud.elementAt(i)));
    if (con1 || con2 || con3) {
    // swap elements
    tmp = (String) choice.elementAt(i);
    choice.setElementAt((String) choice.elementAt(j),i);
    choice.setElementAt(tmp,j);
    tmp = (String) marks.elementAt(i);
    marks.setElementAt((String) marks.elementAt(j),i);
    marks.setElementAt(tmp,j);
    tmp = (String) stud.elementAt(i);
    stud.setElementAt((String) stud.elementAt(j),i);
    stud.setElementAt(tmp,j);
    kindly point the mistake or suggest a better code.
    thanks.

    You can't store your data in three different Vectors because it seems that your data are linked between them.
    As it was said, you should use a class to represent a Student :
    public class Student implements Comparable {
         public String name;
         public float mark;
         public int choice;
         public Student(String n, float m, int c) {
              name = n;
              mark = m;
              choice = c;
         public int compareTo(Object o) throws ClassCastException {
              if (o instanceof Student) {
                   Student st = (Student)o;
                   int compName = name.compareTo(st.name);
                   if (compName == 0) {
                        int compMark = mark>st.mark?1:(mark<st.mark?-1:0);
                        if (compMark == 0) {
                             return(choice>st.choice?1:(choice<st.choice?-1:0));
                        return(compMark);
                   return(compName);
              throw new ClassCastException("The object is not a Student");
    }After that you have just use :
    Collections.sort(studentVector);
    Denis

  • Radix sort and deletions

    Strange problem here (but YAY it compiles G)...and I think it's in the delete method but I am not a hundred percent sure...
    I have a linked list that hold 5 pieces (word, date, orig, pos, def) of data per each linked list line. I also have a vector list that just holds the word itself for all entries into the dictionary. So, the theory is that I should be able to do a radixSort (or any other sort) on the vector and take what the vector returns and create a new list from the old linked list. Does that make sense?
    My list (from a text file) looks sort of like this...
    chereba;verb;to dance;05/02;jon smith;
    semrka;verb;to speak;03/01;jim jones;
    chersl;verb;to laugh;02/01;nancy doe;
    And when I run the print command in the main menu, I get this...
    Chapter c
    chersl (verb) to laugh 02/01
    nancy doe.
    chersl (verb) to laugh 02/01
    nancy doe.
    chersl (verb) to laugh 02/01
    nancy doe.
    Chapter s
    semrka (verb) to speak 03/01
    jim jones.
    chereba (verb) to dance 05/02
    jon smith.
    I think the problem is with the remove method...I don't think that it is doing what it is supposed to do...but I could be way off my rocker and totally missing what the real problem is. Can someone please take a look at this and shove me in the right direction?
    import java.util.Vector;
    public class neverishDictionary
        private Node head;
        public neverishDictionary()
             head = null;
        //begin inner node class
        private class Node
             private String word, pos, def, date, org;
             private Node next;
             public Node(String word1, String pos1, String def1, String date1, String org1)
             //1st constructor
                word = word1;
                pos = pos1;
                def = def1;
                date = date1;
                org = org1;
                next = null;
            public Node(String word1, String pos1, String def1, String date1, String org1, Node nextNode)
            //2nd constructor
                word = word1;
                pos = pos1;
                def = def1;
                date = date1;
                org = org1;
                next = nextNode;
            public String getWord()
                return word;
            public String getPos()
                return pos;
            public String getDef()
                return def;
            public String getDate()
                return date;
            public String getOrg()
                return org;
            public void setNext(Node nextNode)
                next = nextNode;
            public Node getNext()
                return next;
       }//ends the inner class
       public boolean isEmpty()
            return head == null;
       public void addList(String newWord, String newPos, String newDef, String newDate, String newOrg)
            Node curr;
            Node prev;
            Node newNode = new Node (newWord, newPos, newDef, newDate, newOrg);
            if(isEmpty())
                newNode.setNext(head);
                head=newNode;
            else
                newNode.setNext(head);
                head=newNode;
      /*      else
                prev = head;
                curr = head;
                while (curr != null)
                  if (newWord.compareTo(curr.getWord())<0)
                      prev.setNext(newNode);
                      newNode.setNext(curr);
                      break;
                   else
                       prev = curr;
                       curr = curr.getNext();
                       if (curr == null)
                           prev.setNext(newNode);
       public void remove(String temp)
            Node prev = head;
            Node curr = head;
            int x = 0;
            while (curr != null)
            if (curr.getWord().equals(temp) && curr == head)
                      String resultWord = curr.getWord();
                      String resultPos = curr.getPos();
                      String resultDef = curr.getDef();
                      String resultDate = curr.getDate();
                      String resultOrg = curr.getOrg();
                      head = curr.getNext();
            else 
                   if (x == 0)
                      temp = curr.getWord();
                      curr = curr.getNext();
                  else if(curr.getWord().equals(temp))
                String resultWord = curr.getWord();
                      String resultPos = curr.getPos();
                      String resultDef = curr.getDef();
                      String resultDate = curr.getDate();
                      String resultOrg = curr.getOrg();
                      curr = curr.getNext();
                else
                     curr=curr.getNext();
                x++;
      public Vector radixSort(Vector vlist)
       final int NUMCHARS = 128;
      // +----------------+------------------------------------------
      // | Public Methods |
      // +----------------+
       * Sort stuff (a vector of strings) alphabetically.
        // Set up the result vector.
        Vector result = (Vector) vlist.clone();
        // Set up the buckets.
        Vector[] buckets = new Vector[NUMCHARS]; 
        for (int i = 0; i < NUMCHARS; i++) {
          buckets[i] = new Vector();
        // Determine the number of strings.
        int numStrings = vlist.size();
        // Find the length of the longest string
        int len = 0;
        for (int i = 0; i < numStrings; i++) {
          String str = (String) result.get(i);
          if (str.length() > len) len = str.length();
        } // for
        // Step through the positions from right to left, shoving into
        // buckets and then reading out again
        for (int pos = len-1; pos >=0; pos--) {
          // Put each string into the appropriate bucket
          for (int i = 0; i < numStrings; i++) {
            String str = (String) result.get(i);
            int bucketnum;
            // If the string is too short, shove it at the beginning
            if (str.length() <= pos)
              bucketnum = 0;
            else
              bucketnum = str.charAt(pos);
            buckets[bucketnum].add(str);
          // Read it back out again, clearing the buckets as we go.
          result.clear();
          for (int i = 0; i < NUMCHARS; i++) {
            result.addAll(buckets);
    buckets[i].clear();
    } // for(i)
    } // for(pos)
    putitback (result);//put the vector into the list
    // That's it, we're done.
    return result;
    } // sort
    //method to pull out the string in the vector, add the other date in it
    //and throw it back onto the list in correct sorted order.
         public void putitback(Vector result)
              String temp = " ";
              Node prev = null;
         Node curr = head;
              for (int x = 0; x < result.size(); x++)
                   temp = result.remove(x).toString();
                   if (curr.getWord().equals(temp));
                   String word = curr.getWord();
                   String pos = curr.getPos();
                   String def = curr.getDef();
                   String date = curr.getDate();
                   String org = curr.getOrg();
                   remove(temp);
                   addList(word, pos, def, date, org);
    public void displayAll()
    //radixSort(vlist);
    Node prev = head;
    Node curr = head;
    String blah = " ";
    while (curr != null)
    if (blah.compareTo(curr.getWord().substring(0,1)) < 0)
         blah = curr.getWord().substring(0,1);
         System.out.println("\nChapter " + curr.getWord().substring(0,1));
    System.out.println(curr.getWord() + " (" + curr.getPos() + ") " + curr.getDef() + " " + curr.getDate());
    System.out.println(" " + curr.getOrg() + ".");
    prev = curr;
    curr = curr.getNext();

    Why not implement the Comparable interface (int compareTo(Object) method) and let the Arrays.sort function handle the sorting?

  • Quick-Sort Algorithm HELP !!!

    hi there, I wrote a method to sort an 2D-Vector. I used the Bubble-Algorithm.
    Here the code:
    Vector == [Micky, Niko, Tete] ; [Lilo, Eli, Micha];
    public static void bubbleSort( Vector v,
    int sortColumn,
    boolean ascending )
    int i = 0,
    j = 0,
    length = v.size();
    Vector tmp1,
    tmp2;
    for (i = 0; i < (length - 1); i++)
    for (j = i+1; j < length; j++)
    tmp1 = (Vector) v.elementAt(i);
    tmp2 = (Vector) v.elementAt(j);
    if (SortUtil.isGreaterThan(tmp1.elementAt(sortColumn), tmp2.elementAt(sortColumn)) > 0)
    // swap
    SortUtil.swap2D(v, i, j);
    public class SortUtil
    public static int isGreaterThan(Object obj1, Object2)
    // String
    if ( (obj1 instanceof String) && (obj2 instanceof String) )
    return ( ((String) obj1).compareTo((String) obj2) );
    public static void swap2D(Vector v, int i)
    Vector tmp = (Vector) v.elementAt(i);
    v.setElementAt((Vector) v.elementAt(i+1), i);
    v.setElementAt(tmp, i+1);
    I want now to write a method to use the quick-sort-algorithm.
    How can I do this.
    thanks a lot.
    micky z.

    Hi
    You can use java.util.Arrays.sort() method to sort an array of data in quick sort algo. May be you will have to use a n array insted of the Vector.
    Use vector.toArray() method to get an array from the vector.
    But if you want to use a dynamically resizing container like the Vector, use a java.util.LinkedList insted of the Vector and use Collections.sort() method
    Good luck.

  • Sort Multiple Times on Hash Table

    I have a hash table that the key is id, value is a string of first name, last name, and age.
    for example:
    Hashtable showHT = new Hashtable();
    showHT.put(person.getId(), person); <--- person is an object that contains all information
    How to do sorting?
    If I want to sort by id, last name, first name, and age, how can I do it.
    I just know how to do once:
    for exmpale, sorting by id:
    Vector v = new Vector(showHT.keySet());
    Collections.sort(v);
    for (int i = 0; i < v.size(); i++)
         Integer key = (Integer) v.get(i);     
         String str = (String) showHT.get(key).toString();
         out.println(key + ": " +  str);
    }How can I do the sorting by id, last name, first name, and age?
    Thank you.

    Given your "design", it is trivial to sort by id -- use a TreeMap .
    Beyond that, you're going to have to face a basic fact: your design sucks. You are abusing Strings.
    You need to:
    1. Define a Person class
    2. Define multiple Person Comparators
    At that point you are essentially done.
    [http://java.sun.com/docs/books/tutorial/collections/algorithms/index.html#sorting]
    edit: or did I misread your vague code snippet? What type is person?

  • Alphabetical sort...

    Hi,
    I would like to sort an array of strings alphabetically.
    String[] fileList = logDirectory.list();
    I wanna sort fileList by name.
    I know i can do it by checking each string and comparing it to the others or sth like that. my question is, is there a java method that can sort an array/vector/... by name?
    thx! :o)

    ok sorry, i just realised that was a really dumb question! all i have to do is use java.util.Arrays.sort( fileList)!!! sorry again lol! :o)

  • Draw lines within a table (repeating group)

    I have a table of 6X6 (rowsxcolumns) built using Word 2010. The cells starting from 2nd row to 5th row are merged and another table is created in this place with a repeating group. This means, the no. of rows this 2nd table would have is dynamic (based on the results)
    Because of the layout requirement, I need vertical lines drawn for each of the columns in table 1 but excluding Row 1 and Row 6 (these are sort of headers). Is there a way to achieve this?
    I tried using "Draw Shapes" and inserting vertical lines in the positions I want. But since this shape is of constant length and 2nd table contains dynamic rows, it isn't working if it has fewer/greater no. of rows.
    Any ideas would be highly appreciated.
    Thanks!

    Ok,
    I will assume that you have a dataVector that contains Vectors that have a String and an Integer in it. You pass this dataVector to the following method, that returns a Vector which contains the same data grouped. I assume also that your dataVector is sorted before:
    public Vector groupVector(Vector dataVector) {
    Vector r;
    Vector v = new Vector(2,2);
    if (dataVector.size()==0) return null; // no data there - return null
    String name = (String) ((Vector) dataVector.elementAt(0)).elementAt(0);
    int sum = 0;
    for (int i = 0; i<dataVector.size();i++)
    { String curname = (String) ((Vector) dataVector.elementAt(i)).elementAt(0);
    if (name.equals(curname))
    { sum += ((Integer) ((Vector) dataVector.elementAt(i)).elementAt(1)).intValue(); }
    else
    { r = new Vector(2);
    r.add(name);
    r.add(new Integer(sum));
    v.add(r);
    name = curname;
    sum = ((Integer) ((Vector) dataVector.elementAt(i)).elementAt(1)).intValue();
    } // end else
    } // end for-loop
    r = new Vector(2);
    r.add(name);
    r.add(new Integer(sum));
    v.add(r);
    return v;
    } // end of methodI have not tested it nor compiled - leave that to you
    Hope this helps
    greetings Marsian

  • Plz need help with this hashmap program

    as far as i know, this hashmap program works, but i cant get it to compile correctly because of one line error:
    phoneArray[2] = int f;
    the second position in phoneArray is and will always be a number, but the array is a String array, making it difficult for me to take the number in that position and change it.
    In actuality, the number is a score (a grade) and i need to take it to change it to a letter grade, where it will later be spit out in order from Name, Year, Score, Grade.
    plz help, this is a school assignment and its driving me mad.
    import java.util.*;
    import java.io.*;
    * A class that represents a phone book.  This phone
    * book maps names to phone numbers.  This will
    * read teh phone book information from a file.
    public class CourseData2 {
      /////////////////// fields ///////////////////
      private String fileName;
      private Map phoneMap = new HashMap();
      /////////////////// constructors ///////////////////
       * Constructor that takes a file name and reads
       * in the names and phone numbers from a file.
       * @param file the name of the file to read
      public CourseData2(String file) {
        this.fileName = file;
        // Read the map information in form the file
        readInfoFromFile();
      } // constructor
      /////////////////// methods ///////////////////
       * Get the phone number for hte passed nam
       * @param name the name to look up in hte map
       * @return the phone number if found, else null
      public String getPhoneNumber(String name) {
        String phoneNumber = (String) phoneMap.get(name);
        return phoneNumber;
      } // method getPhoneNumber()
       * Method to read the phone information from a
       * file and use it to fill hte map
      public void readInfoFromFile() {
        String line = null;
        String[] phoneArray = null;
        try {
          // create the reader
          BufferedReader reader =
            new BufferedReader(new FileReader(fileName));
          // loop reading from the file
          while ((line = reader.readLine()) != null) {
            if (line.indexOf(":") >= 0) {
              phoneArray = line.split(":");
              phoneMap.put(phoneArray[0].trim(),
                           phoneArray[1].trim(),
                           phoneArray[2].trim());
            } // if
            } // while
            (int)phoneArray[2] = int f;
            if (f < 60) { (String)a = "E";}
            else if (60 <= f < 70) { (String)f = "D";}
            else if (70 <= f < 80) { (String)f = "C";}
            else if (70 <= f < 90) { (String)f = "B";}
            else if (90 <= f) { (String)a = "A";}
          // Close the reader
          reader.close();
        } // try
        catch (FileNotFoundException ex) {
          SimpleOutput.showError("Could not find the file \"" + fileName + "\".");
        } // catch
        catch (Exception ex) {
          ex.printStackTrace();
        } // catch
      } // method readInfoFromFile()
      public void printBook() {
        // Sort hashtable.
        Vector phoneVector = new Vector(phoneMap.keySet());
        Collections.sort(phoneVector);
        // Display (sorted) hashtable.
        for (Enumeration phoneEnumeration = phoneVector.elements(); phoneEnumeration.hasMoreElements();) {
          String key = (String)phoneEnumeration.nextElement();
          System.out.println("Name: " + key + ", Year: " + phoneMap.get(key) + ", Score: " + phoneMap.get(key) + ", Grade: " + phoneMap.get(key));
        } // for
      } // method printBook()
      /* main method for testing */
      public static void main(String[] args) {
        CourseData2 phoneBook = new CourseData2("scores12.txt");
        System.out.println(phoneBook.getPhoneNumber("Lee"));
        System.out.println(phoneBook.getPhoneNumber("Smith"));
        phoneBook.printBook();
      } // main()
    } // class

    after much time and editing, this is the revised coding:
    import java.util.*;
    import java.io.*;
    * A class that represents a class score book.  This
    * book maps names to scores and grades.  This will
    * read the names, scores and grade information from a file.
    public class CourseData2 {
      /////////////////// fields ///////////////////
      private String fileName;
      private Map phoneMap = new HashMap();
      /////////////////// constructors ///////////////////
       * Constructor that takes a file name and reads
       * in the names and phone numbers from a file.
       * @param file the name of the file to read
      public CourseData2(String file) {
        this.fileName = file;
        // Read the map information in form the file
        readInfoFromFile();
      } // constructor
      /////////////////// methods ///////////////////
       * Get the phone number for hte passed nam
       * @param name the name to look up in hte map
       * @return the phone number if found, else null
      public String getPhoneNumber(String name) {
        String phoneNumber = (String) phoneMap.get(name);
        return phoneNumber;
      } // method getPhoneNumber()
       * Method to read the phone information from a
       * file and use it to fill hte map
      public void readInfoFromFile() {
        String line = null;
        String[] phoneArray = null;
        String a = "";
        try {
          // create the reader
          BufferedReader reader =
            new BufferedReader(new FileReader(fileName));
          // loop reading from the file
          while ((line = reader.readLine()) != null) {
            while ((line = reader.readLine()) != null) {
            if (line.indexOf(":") >= 0) {
              phoneArray = line.split(":");
              int f = Integer.parseInt(phoneArray[2]);
              if (0 <= f && f <= 100) {
            if (0 <= f && f < 60) { a = "E";}
            else if (60 <= f && f < 70) { a = "D";}
            else if (70 <= f && f < 80) { a = "C";}
            else if (80 <= f && f < 90) { a = "B";}
            else if (90 <= f && f <= 100) { a = "A";}
              } // if f between 0 and 100
            else if ( f > 100 && f < 0 )  {
            SimpleOutput.showError("Score is not an integer");
            String g = new String();
            g = phoneArray[2];
              }//if < 0
            }// if (line.index....
            phoneMap.put(phoneArray[0].trim(),
                        (phoneArray[1].trim() + phoneArray[2].trim() + (String)a));
            } // while2
            } // while
          // Close the reader
          reader.close();
        } // try
        catch (FileNotFoundException ex) { 
          SimpleOutput.showError("Could not find the file \"" + fileName + "\".");
        } // catch
        catch (Exception ex) {
          ex.printStackTrace();
        } // catch
      } // method readInfoFromFile()
      public void printBook() {
        // Sort hashtable.
        Vector phoneVector = new Vector(phoneMap.keySet());
        Collections.sort(phoneVector);
        // Display (sorted) hashtable.
        for (Enumeration phoneEnumeration = phoneVector.elements(); phoneEnumeration.hasMoreElements();) {
          String key = (String)phoneEnumeration.nextElement();
          System.out.println("Name: " + key + ", Year: " + phoneMap.get(key) + ", Score: " + phoneMap.get(key) + ", Grade: " + phoneMap.get(key));
        } // for
      } // method printBook()
      /* main method for testing */
      public static void main(String[] args) {
        CourseData2 phoneBook = new CourseData2("scores12.txt");
        System.out.println(phoneBook.getPhoneNumber("Depp"));
          System.out.println(phoneBook.getPhoneNumber("Gonzales"));
            System.out.println(phoneBook.getPhoneNumber("Jenkins"));
                System.out.println(phoneBook.getPhoneNumber("Lee"));
                   System.out.println(phoneBook.getPhoneNumber("Mac Donald"));
                      System.out.println(phoneBook.getPhoneNumber("O'Malley"));
                         System.out.println(phoneBook.getPhoneNumber("Price"));
                            System.out.println(phoneBook.getPhoneNumber("Ramesh"));
                                System.out.println(phoneBook.getPhoneNumber("Smith"));
                                    System.out.println(phoneBook.getPhoneNumber("Winston"));
        phoneBook.printBook();
      } // main()
    } // classthis has no errors, but gives me 4 warnings, which i can't solve, plz help

  • Better code for hashtables

    Hi all.
    I have a vector which contains a lot of string. Then i have another string which is called keyword. So, for example:
    Vector v = new Vector();
    v.add("Sam went to the hospital today");
    v.add("They told him he had the flu");
    v.add("The hospital had arranged now arranged a second meetin")
    v.add(" Sam will come back then");
    String Key =  " hospital;What i need to do is find in which vector position does hospital occur and give it a score. So i also need a way of storing the sentence again and assigning it a value i.e. (Sam went to the hospital today, 20). The value is preset. Any help would be much appreciated. Many thanks.

    hi,
    here i am giving example on hash table.
    please follow.
    import java.util.*;
    public class SortHashtable {
    public static void main(String[] args) {
    // Create and populate hashtable
    Hashtable ht = new Hashtable();
    ht.put("abc",new Double(3445.23));
    ht.put("xyz",new Double(2333.56));
    ht.put("pqr",new Double(3900.88));
    ht.put("mno",new Double(2449.00));
    // Sort hashtable.
    Vector v = new Vector(ht.keySet());
    Collections.sort(v);
    // Display (sorted) hashtable.
    for (Enumeration e = v.elements(); e.hasMoreElements();) {
    String key = (String)e.nextElement();
    System.out.println(key+":"+ht.get(key));
    System.out.println();
    i hope u get what u want
    jp reddy

  • Passing several fields to various classes and methods?

    Passing several fields to various classes and methods?
    Hi there.
    I have an application that allows a user to define a configuration and save it.
    The user can edit an existing configuration, add a new one, or delete an existing one.
    Once a configuration is selected the user then starts an application that relies on the selected configuration data. Each configuration holds around 60 fields.
    The configuration information is mixed between integers and strings. Around 25 are hidden from the user, and 35 can be modified by the user. The number of fields is not a fixed amount. For example the configuration contains an email-to list and the list for one configuration can have 1 address, and for another could have 10 addresses.
    I have decided to redesign using the Model View Controller concept. I am creating the model to hold the configuration information. I am trying to decide if I should have single get and set methods for each field or if I should create some kind of Object that holds all of one configuration and pass this back.
    The configuration that is selected does not really require the fields to be sorted in any particular order.
    What would you suggest is a good structure to use to pass the configuration information around?
    I have been using the Properties class with an .ini file that can be read and updated.
    Is this efficient? Doesn�t this impact the speed of processing if I have to read a file every time I want to determine what a particular configuration field is?
    Could I just create a class that reads the profile, stores the configuration information for one specific selected config, and then passes the class back to the calling procedure. This would consolidate all the file reading into one class and after that it is held in memory.
    Would it be better to read the configuration information into a collection of some sort , or a vector and pass this back to calling routine?
    public class MyModel {
         //read information to load the field of
         Private MyConfig selectedConfiguration = new MyConfig;
            Private int     selectedField1 = 0;
            /** Constructor */
         MyModel() {
              // open profile, read profile fields the
              selectedConfiguration.field1 = profileField1;  //assume this is 5
                    selectedConfiguration.field2 = profileField2;  //assume this is 10
              selectedConfiguration.field3 = �Test�;
                    field4ArrayOfStrings  = new String[selectedConfiguration.field1 ]
                                                                 [selectedConfiguration.field2];
              selectedConfiguration.field3ArrayOfStrings [0][0] = �First String�
         public class MyConfig(){
         int field1;
         int field2;
         String field3;
         String[][] field4ArrayOfStrings;
         // more stuff here �.
         // selectedConfiguration
         public void setConfiguration(MyConfig p_config) {
              String selectedConfiguration = p_config;
         public String getConfiguration() {
              return selectedConfiguration;
         //The other option is to have get and set for each field
         public void setField1(int field1) {
              String selectedField1 = field1;
         public String getField1() {
              return selectedField1;
    }Slight correction: reference to field3ArrayOfStrings changed to field4ArrayOfStrings.
    Message was edited by:
    tkman

    johndjr wrote:
    I think the term you want is "cross reference".
    Back in the olden days of green bar paper listings and linker maps they used to be quite common. At least they were where I worked.
    I have not seen any cross references in some time.
    java.lang.Object grr_argh_why_I_oughta_you_dirty_rat; // a pretty cross reference

  • Jtable column title

    I want to sort a JTable by clicking a column title
    (sort according to that column's values)
    I thought about adding an actionListener to the titles
    and then sort my data Vector and use fireTableChanged().
    is there a better way, does a JTable have a method to do it on it's own ?

    i like how you show people's incompetence by replying with links to their answers all the time.

  • Why Fireworks?

    I am learning Photoshop for the web and was moving to Dreamweaver tutorials.
    I do not understand why one needs Fireworks. Why do you need to build a prototype of a site, if you can move directly from PShop to Dreamwaver?
    Thanks.

    Jim, Pixlor: Okay, I see what you mean about people expecting Fireworks to convert the site well and why Adobe calls it prototyping. In that case Photoshop and Fireworks can both prototype so Adobe should stop making confusing claims. Fireworks is an excellent design software first - anything else that it additionally offers are bonuses.
    Pendue: Dreamweaver doesn't really "do the rest", you still need to learn HTML and CSS to create professional websites - Dreamweaver does help (like a lot of other website development software) but you need to help yourself by learning to code websites a little - its not that tough and is amazingly interesting :-) I can see that you were searching for reasons why Fireworks can be used and when. Well there are several reasons one of which I was trying to highlight and it got lost in the whole scenario about prototyping. Fireworks is a vector based design software that was made for web design because it renders as for the web. It also rivals illustrator when it comes to graphic design and is better when it comes to designing graphics and vectors for the web because of its pixel perfect vector control. Its not great for photo manipulation and comes nothing close to what Photoshop has in the special effects department. But there are some pretty good reasons to use it in tandem with Photoshop.
    A)  Fireworks is easy to use and not as complicated as Photoshop. Hard to admit but I've tried using Photoshop in the past 6 years occasionally to design a complete website but every-time I'm stumped by why its so difficult to work with. To name a few:
    Vectors are not vectors but masked layers. Duh?! Beats me why Adobe never used the drawing capabilities of Illustrator in Photoshop?
    You can't click and select a visible item. You need to click its layer, super weird. Especially when you have a couple of hundred layers - boy are u lost. Comparatively Fireworks can not only select any visible item on clicking but you can even select items hidden behind other items using the "Select Behind Tool". In PS you never know what is selected but in FW the selection can be visibly discerned.
    Gradients are difficult to manipulate in PS. In Fireworks they are easy to use and you can visually manipulate them easily with the Gradient handles that appear.
    Some simple filters that are non-destructive in FW are destructive in PS. For example Convert to Alpha.
    Neither stroke nor fill can be given without popping a panel. Shouldn't it be visible and changeable with an eye-dropper by instinct.
    Undo steps (Ctrl-z) is just 2. Super weird. You need to use history panel constantly.
    Subselection and moving of grouped items not possible without ungrouping and selecting layer.
    In short: Photoshop requires too many steps for too many tasks.
    B) Vector shapes and manipulation are too basic - check out the autoshapes in Fireworks - they make your job so easy. Especially the ease with which you can change properties like roundness, sides, corner type, etc. whenever you want. And in PS you can't do any sort of multiple vectors manipulation. In FW you just need to click and drag with the sub-selection tool to select any number of points belonging to any number of vectors in the area selected. Its a must to try out the Path Panel features and the advanced autoshapes in the Shapes panel to see its unique features (sorry too many to discuss). The reason I have put the vector capability as a separate point is because a huge part of website design involves drawing shapes which should preferably be vectors. The more you learn website design the more you'll get the hang of creating amazing high-impact designs built with dozens of subtle tiny effects - that's what Web 2.0 design is all about - subtlety and elegance.
    C) Control over your elements is amazing in Fireworks - You have everything at your fingertips the dimensions, the positions, effects, color, stroke, you name it: mostly everything is right there for you to see in the properties panel. If you seek pixel perfection FW is the perfect tool. Finally: Slicing, optimizing and exporting your images is extremely easy (easier than PS if I dare say).
    Hope this helps.
    - Anita
    Important note to the other expert designers - I hope I haven't been too critical of Photoshop - I know most designers use Photoshop with élan. I really would love to love Photoshop but I find it so difficult to get along with ;-) and so I use it only for creating photo effects and jazzy backgrounds. I guess rapidly designing in Fireworks for 11 years has made me a bit impatient with PS. I tried reading dozens of tutorials in futility and I've never been good at using or remembering shortcuts.  If I've made errors in the points above please point them out.

Maybe you are looking for

  • ALV to Excel

    I am using the function module REUSE_ALV_GRID_DISPLAY to display the results of a report I created.  The columns show up on the screen in the order of my field catalog, but I noticed when I go to List --> Export --> Spreadsheet at the top of the scre

  • Display icons in dvt:scheduledGantt taskbar

    Hi, Jdev 11.1.1.2.0. I want to display an icon within the taskbar of scheduledGantt. My VO has a attribute "icon1" with the value "/css/icons/exception.png". This attribute is assigned to the "icon1"-property of the gantt (in the Task section). Thoug

  • How do I display SharePoint ratings (Rating 0-5) on a page?

    Hi, I want to display SharePoint ratings on a page, like in this example https://sharepoint.microsoft.com/en-us/Pages/Videos.aspx   I've enabled ratings in a SharePoint List (for my videos) and I just want to use those ratings ( Rating (0-5) ) on a p

  • Junk Mail filter can't handle high volume

    I use Mail.app at work/school. Unfortunately, my email address there is [email protected], and because it's so simple spammers have taken to sending spam that looks like it came from me. So every day I get dozens to hundreds of bounces from their spa

  • Excluding the initiator in SAP work flow

    Hi, I have a standard sap work flow WS20000263 which has  rule 20000053. How do i exclude the initiator  in this case . Thanks, Pradeep.