Problem sorting

Hi i am trying to sort a collection in two different ways one is by natural ordering and another is by a adoption cost which i calculate the collection is fine it is just when i go to sort the collection for cost that it fails what am i doing wrong
Comparator myCostComp = new CostComparator();
                    if(sort.equals(id)) {       // sort by 'natural' order of the objects in dogList
                              Collections.sort(dogList);
                    } else{                      // sort by cost using my costComparator
                              Collections.sort(dogList, myCostComp);
public class CostComparator implements Comparator {
public int compare(Object o1, Object o2) {
int cost1 = ((Dog)o1).calculateCost ();
int cost2 = ((Dog)o2).calculateCost ();
return cost1 - cost2;

sorry well i am trying to sort a collection that i already have created i am using jsp and java in packages belew i the jsp code i can get it to order the collection via id which equal natural ordering but when i set my form to order the collection via adoption cost it doestn work this is the "cost " variable.
<%@ page language="Java" import="java.util.*,dogAdopt.*" %>
<%
//Process
List dogList = (ArrayList)application.getAttribute("myDogList");
if (dogList == null) {
dogList = new ArrayList();
application.setAttribute("myDogList", dogList);
%>
<html>
<head>
</head>
<body>
<jsp:include page="header.html" />
<form method="post" action="<%pageContext.getPage();%>">
<p>
<label>Please select how you would like to order the table
<select name="sort">
<option value="id">natural ordering</option>
<option value="cost">order by adoption cost</option>
</select>
</label>
</p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
<jsp:useBean id="myDog" class="dogAdopt.Dog" scope="page"/>
     <jsp:setProperty name="myDog" property="*"/>
     </jsp:useBean>
<%
String sort = "notsorted";
String id = "";
String cost = "";
Comparator myCostComp = new CostComparator();
if(!request.getMethod().equals("POST")){
     Collections.sort(dogList);
if(request.getMethod().equals("POST")){
          if(sort.equals(id)) {       // sort by 'natural' order of the objects in dogList
               Collections.sort(dogList);
          if(sort.equals(cost)){                      // sort by cost using my costComparator
               Collections.sort(dogList, myCostComp);
if (dogList.size() == 0){ %>
     <p>No dogs in collection</p>
     <%}else{%>
          <TABLE cellSpacing=1 cellPadding=0 width=741 border=1>
               <TBODY>
               <TR align=left>
                    <TH><B>Dog ID</B></TH>
                    <TH><B>Breed</B></TH>
                    <TH><B>Temperament</B></TH>
                    <TH><B>Neutered?</B></TH>
                    <TH><B>Age</B></TH>
                    <TH><B>Length of stay</B></TH>
                    <TH><B>Adoption cost</B></TH>
                    <TH><B>Image</B></TH>
               </TR>
               <%
                    ListIterator litr = dogList.listIterator(0);
                    while(litr.hasNext()) {
                         Dog nextDog = (Dog)litr.next();%>
                         <TR vAlign=top>
                              <TD><%=nextDog.getId()%></TD>
                              <TD><%=nextDog.getBreed()%></TD>
                              <TD><%=nextDog.getTemperament()%></TD>
                              <TD><%=nextDog.isNeutered()%></TD>
                              <TD><%=nextDog.getAge()%></TD>
                              <TD><%=nextDog.getStay()%></TD>
                              <TD><%=nextDog.calculateCost()%></TD>
                              <TD><DIV align=center><IMG height=100 src="<%=nextDog.getImage()%>"></DIV></TD>
                         </TR>
                    <%}%>
</TBODY>
</TABLE>
                    <br>
<%} //endif %>
</body>
</html>

Similar Messages

  • Problem sorting data in a file?

    I have a problem sorting this file alphabetically by second name. Basically, my method sorts each column alphabetically but i would like to sort the file according to the second name. I really really need help. Thanks
    File:
    Moe     Carl
    Saul     Sergio
    Rocky     Louis
    Ike     Ziken     
    This is how my method sorts the file:
    Ike          Carl
    Moe          Louis
    Rocky          Sergio
    Saul          ziken
    Instead
    Moe     Carl
    Rocky      Louis
    Saul     Sergio
    Ike     Ziken
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    class thedata implements Comparable
              private String firstname;
              private String secondname;
        public void setFirstname(String firstname)
                 this.firstname = firstname;
        public String getFirstname()
                  return firstname;
        public void setSecondname(String secondname)
                this.secondname = secondname;
        public String getSecondname()
                return secondname;
        public int compareTo(Object Student) throws ClassCastException
                if (!(Student instanceof ShowData))
                throw new ClassCastException("Error");
                String sn = ((ShowData) Student).getSecondname();
                return this.secondname.compareTo(sn);
    public class sort {
            public static void main(String[] args) {
            sortmethod();
            public static void sortmethod(){
              int j = 0;
              thedata data[] = new thedata[4];
             try
                      FileInputStream fstream = new FileInputStream("datafile.txt");
                      DataInputStream in = new DataInputStream(fstream);
                      BufferedReader br = new BufferedReader(new InputStreamReader(in));
                      String line;
                      String[] firstname = new String[4];
                      String[] secondname = new String[4];
                      ArrayList<String> list = new ArrayList<String>();
                      while ((line = br.readLine()) != null)
                              list.add(line);
                      Iterator<String> itr = list.iterator();
                      int k = 0;
                      for (itr = list.iterator(); itr.hasNext();)
                              String str = itr.next().toString();
                              String[] splitSt = str.split("\t");
                     for (int i = 0; i < splitSt.length; i++)
                                 firstname[k] = splitSt[0];
                                 secondname[k] = splitSt[1];
                      k++;
                      arraysort(firstname);
                      arraysort(secondname);
                         for(j = 0;j < 4;j++)
                                 data[j] = new thedata();
                                 data[j].setFirstname(firstname[j]);
                                 data[j].setSecondname(secondname[j]);
                      for (int i = 0; i < 4; i++)
                                 thedata show = data;
                             String firstname1 = show.getFirstname();
                             String secondname1 = show.getSecondname();
                                  System.out.println(firstname1 + "\t\t" + secondname1);
                        catch (Exception e)
         private static void arraysort(String[] array)
              for(int i=0; i<array.length; i++)
                   for(int j=0; j<array.length-1-i; j++)
                        if(array[j].compareTo(array[j+1])>0)
                                  String temp1 ="";
    temp1= array[j];
    array[j] = array[j+1];
    array[j+1] = temp1;
    Edited by: 999363 on Apr 11, 2013 3:41 AM

    You're not sorting your objects, you're only sorting the firstname and secondname arrays separately, so they get scrambled. Sort the array of `thedata` objects.
    BTW this:
        public int compareTo(Object Student) throws ClassCastException
                if (!(Student instanceof ShowData))
                throw new ClassCastException("Error");
                String sn = ((ShowData) Student).getSecondname();
        }contains a complete waste of time. You should just remove 'throws ClassCastException' and the first two lines of the method. The test and throw happens anyway at the cast. If Student isn't an instance of ShowData the cast will fail with the same exception (and a much better error message).

  • Problem sorting list with virtual layout = false (and also with true)

    Hi,
    I've a problem sorting a list... or better... I've a problem showing the sorted list ;-)
    I've a list of xml item. The list is shown with an item renderer.
    my needs: a button to refresh data and a button to sort data.
    useVirtualLayout = false
    -> refresh works correctly, sort does not affect the view (even if the list is sorted correctly when printed with trace)
    useVirtualLayout = true
    -> sort works correctly, refresh reverse the list each time I press it (even if the list remain the same when printed with trace)
    does any one have an idea?
    thank you!!
    MXML
    <s:List dataProvider="{xmlListCollection}" width="100%" itemRenderer="myRenderer" minHeight="0" id="test" useVirtualLayout="false" >
    <s:layout>
      <s:VerticalLayout clipAndEnableScrolling="true"/>
    </s:layout>
    </s:List>
    XML example
    <unit sortField1="First Floor" sortField2="7">
      <employee>
        <id>3040684</id>
        <name>PIFFARETTI Vasco</name>
        <birthdate>20.05.1983</birthdate>
        <beginDate>2012-02-25 08:55:00</beginDate>
        <endDate>9999-12-31 00:00:00</endDate>
        <annotation/>
      </employee>
    </unit>

    You can tell when the scroll position has changed by handling the propertyChange event coming from the DataGroup:
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   creationComplete="list1.dataGroup.addEventListener('propertyChange', handle)">
        <fx:Script>
            <![CDATA[
                import mx.events.PropertyChangeEvent;
                private function handle(e:PropertyChangeEvent):void {
                    if (e.property == 'verticalScrollPosition'){
                        trace('vsp changed');               
                    if (e.property == 'horizontalScrollPosition'){
                        trace('hsp changed');               
            ]]>
        </fx:Script>
        <s:List id="list1" width="100" height="50">
            <s:layout>
                <s:VerticalLayout />
            </s:layout>
            <s:dataProvider>
                <s:ArrayList>
                    <fx:String>0</fx:String>
                    <fx:String>1</fx:String>
                    <fx:String>2</fx:String>
                    <fx:String>3</fx:String>
                    <fx:String>4</fx:String>
                    <fx:String>5</fx:String>
                    <fx:String>6</fx:String>
                    <fx:String>7</fx:String>
                </s:ArrayList>
            </s:dataProvider>
        </s:List>
    </s:Application>
    You might also want to read and consider voting for http://bugs.adobe.com/jira/browse/SDK-21357

  • I'm having problems Sorting Objects

    Hello everyone!
    I'm having problems sorting objects. Here is what I got at moment... I'm trying using "Collections.sort" with objects, and I think my problem is there but I don't know how to do in other way the sorting.
    Some help will be appreciated! Thank you!
    Movie.java
    import java.util.ArrayList;
    public class Movie
             public int itemNum;
             private String title;
             public String director;
             public Movie()
                 itemNum = -1;
                 title = "";
                 director = "";
             public Movie(int itemNum, String title, String director)
                this.itemNum = itemNum;
                this.title = title;
                this.director = director;
             public int getItemNum()
                 return itemNum;
             public String getTitle()
                 return title;
             public String getDirector()
                 return director;
               public void setItemNum(int a)
                  itemNum = a;
             public void setTitle(String b)
                 title = b;
             public void setDirector(String c)
                 director = c;
             public String toString()
                   String MovieInfo = title + "\t" + itemNum + "\t" + director ;
                   return MovieInfo;
    }MovieCollection.java
    import java.util.*;
    public class MovieCollection
        private ArrayList Movies;
         public MovieCollection()
                Movies = new ArrayList();
         public ArrayList getMovies()
                return Movies;
         public void add(Movie aMovie)
                Movies.add(aMovie);
    }MovieCollectionMenu.java
    import java.io.*;
    import java.util.*;
    public class MovieCollectionMenu
              private MovieCollection model;
              public MovieCollectionMenu ()
                   model = new MovieCollection();
            public MovieCollection getModel()
                return model;
             private static Scanner Insert = new Scanner(System.in);
              public static void main (String[] args)
                  MovieCollectionMenu menu = new MovieCollectionMenu();
                   while(true)
                 System.out.println("Movies Menu");
                 System.out.println("");     
                 System.out.println("1 - Add Movie");
                 System.out.println("2 - List Movies");
                 System.out.println("3 - Sort Movies");
                 System.out.println("0 - Exit");
                    System.out.print("\nSelect your option: ");
                 int option = Insert.nextInt();
                      switch(option)
                           case 0:   System.exit(0);break;
                         case 1:   menu.addMovie(); break;
                         case 2:   menu.listMovies(); break;
                         case 3:   menu.sortMovie(); break;
                         default:  System.out.println("Invalid Selection!");
                      System.out.println("\n");
              private void addMovie()
                   Movie aMovie = new Movie();
                System.out.print("\nEnter movie name: ");
                   aMovie.setTitle(Insert.next());
                 System.out.print("Enter number of copies: ");
                aMovie.setItemNum(Insert.nextInt());
                System.out.print("Enter director name: ");
                aMovie.setDirector(Insert.next());
                model.add(aMovie);
            private void listMovies()
                   ArrayList Movies = model.getMovies();
                   for (int i=0; i<Movies.size(); i++)
                        System.out.println(Movies.get(i).toString());
              private void sortMovie()
                 ArrayList Movies = model.getMovies();
                 Collections.sort(Movies);
    }

    JBStonehenge, Melanie_Green, paulcw thank u so much for ur support!!!!
    I did many changes in my code, and I think in a simple way... I can sort the strings, but I'm having problems to sort the integers from the array I created..
    I read a lot of sorting and this was the best I could do, please can you change my code to sort the integers?
    Thank u people!
    Here it is my code:
    import java.io.*;
    import java.util.*;
    public class MyMovies {
         public static void main(String[] args) {
              MyMovies Movies = new MyMovies();
              Movies.runEverything();
         private static final int MAX_SIZE = 100;
         private static int numberOfMovies = 0;
         private static Movie[] array = new Movie[MAX_SIZE];
         public void runEverything(){
              Scanner input = new Scanner(System.in);
              while (true) {
                   Menu();
                   int option;
                   try {
                        option = Integer.parseInt(input.nextLine());
                   } catch (NumberFormatException e) {
                        System.out.println("You must enter a number!");
                        continue;
    switch (option) {
                   case 1:
                        addMovie(input);
                        System.out.println("\nThis movie was added:");
                        printMovie(numberOfMovies - 1);
                        break;               
                   case 2:
                        sortMoviesByTitle();
                        break;
                   case 3:
                        sortMoviesByYear();
                        break;
                   case 4:
                        sortMoviesByDirector();
                        break;
                   case 5:
                        printAllMovies();
                        break;
                   case 6:
                        System.out.println("You logout with success!");
                        input.close();
                        System.exit(0);
                        break;
              default:
                        System.out.println("You entered a wrong option! Please try again.");
                        break;
         private static void Menu() {
              System.out.println("\n1 - Add a movie");
              System.out.println("2 - Sort movies by name");
              System.out.println("3 - Sort movies by year");
              System.out.println("4 - Sort movies by director");
              System.out.println("5 - Display movies");
              System.out.println("6 - Quit");
              System.out.print("\nPlease enter an option:");
              private static void printMovie(int i) {
              if (i < numberOfMovies) {
                   System.out.println("\"" + array.getTitle() + "\", " + array[i].getYear() + ", \"" + array[i].getDirector() + "\"");
         private void printAllMovies() {
              for (int i = 0; i < numberOfMovies; i++) {
                   System.out.print(String.valueOf(i+1) + "-");
                   printMovie(i);
         private static void addMovie(Scanner input) {
              System.out.print("Enter movie:");
              String title = input.nextLine();
              int year = 0;
              while (true) {
                   try {
                        System.out.print("Enter the year of movie:");
                        year = Integer.parseInt(input.nextLine());
                        break;
                   } catch (NumberFormatException e) {
                        System.out.println("You must enter an integer!");
                        continue;
              System.out.print("Please enter the director:");
              String director = input.nextLine();
              array[numberOfMovies] = new Movie(title, year, director);
              numberOfMovies++;
         private void sortMoviesByTitle(){
         boolean swapped = true;
              int i = 0;
              String tempTitle, tempDirector;
              int tempYear;
              while (swapped) {
                   swapped = false;
                   i++;
                   for (int j = 0; j < numberOfMovies - i; j++) {
                        if ( array[j].getTitle().compareToIgnoreCase(array[j + 1].getTitle()) > 0) {   
                             tempTitle = array[j].getTitle();
                             tempYear = array[j].getYear();
                             tempDirector = array[j].getDirector();
                             array[j].setTitle(array[j + 1].getTitle());
                             array[j].setYear(array[j + 1].getYear());
                             array[j].setDirector(array[j + 1].getDirector());
                             array[j + 1].setTitle(tempTitle);
                             array[j + 1].setYear(tempYear);
                             array[j + 1].setDirector(tempDirector);
                             swapped = true;
              System.out.println("The movies are sorted by title.");
         private void sortMoviesByYear(){
         boolean swapped = true;
              int i = 0;
              String tempTitle, tempDirector;
              int tempYear;
              while (swapped) {
                   swapped = false;
                   i++;
                   for (int j = 0; j < numberOfMovies - i; j++) {
                        if ( array[j].getYear().compareToIgnoreCase(array[j + 1].getYear()) > 0) {   
                             tempTitle = array[j].getTitle();
                             tempYear = array[j].getYear();
                             tempDirector = array[j].getDirector();
                             array[j].setTitle(array[j + 1].getTitle());
                             array[j].setYear(array[j + 1].getYear());
                             array[j].setDirector(array[j + 1].getDirector());
                             array[j + 1].setTitle(tempTitle);
                             array[j + 1].setYear(tempYear);
                             array[j + 1].setDirector(tempDirector);
                             swapped = true;
              System.out.println("The movies are sorted by year.");
         private void sortMoviesByDirector(){
         boolean swapped = true;
              int i = 0;
              String tempTitle, tempDirector;
              int tempYear;
              while (swapped) {
                   swapped = false;
                   i++;
                   for (int j = 0; j < numberOfMovies - i; j++) {
                        if ( array[j].getDirector().compareToIgnoreCase(array[j + 1].getDirector()) > 0) {   
                             tempTitle = array[j].getTitle();
                             tempYear = array[j].getYear();
                             tempDirector = array[j].getDirector();
                             array[j].setTitle(array[j + 1].getTitle());
                             array[j].setYear(array[j + 1].getYear());
                             array[j].setDirector(array[j + 1].getDirector());
                             array[j + 1].setTitle(tempTitle);
                             array[j + 1].setYear(tempYear);
                             array[j + 1].setDirector(tempDirector);
                             swapped = true;
              System.out.println("The movies are sorted by director.");
    /* ----- My Movie Class ----- */
    class Movie {
         private String title;
         private int year;
         private String director;
         public Movie(String title, int year, String director) {
              setTitle(title);
              setYear(year);
              setDirector(director);
         public String getTitle() {
              return title;
         public void setTitle(String title) {
              this.title = title;
         public int getYear() {
              return year;
         public void setYear(int year) {
              this.year = year;
         public String getDirector() {
              return director;
         public void setDirector(String director) {
              this.director = director;
    }Edited by: AntiSignIn on Mar 24, 2010 7:30 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problem sorting items in finder window

    I've searched other posts and seen that others are having similar issues however, I can't a solution to my problem.
    In a finder window in list view, in the upper part of the window, I have Name, Date Modified, Size and Kind.  Before I upgraded to Mavericks, I could click any of those options and the window would sort accordingly.  Now, if I want to sort a window, I have to open the view options and do it that way.  The weird thing is, I have a RAID connected via esata and it works like it should on any window I open from that drive.  Any suggestions?

    Might be corrupted Finder preferences.
    Open the Finder. From the Finder menu bar click Go > Go to Folder
    Type or copy paste the following:
    ~/Library/Preferences/com.apple.finder.plist
    Click Go then move the com.apple.finder.plist file to the Trash.
    Restart your Mac then try the Finder.

  • Problems sorting custommade linkedlist

    Hi guys, I have a problem (obviously).
    Its an assignment for school and I'm supposed to write my own LinkedList (called PhoneDirectory) instead of using the already defined one in java. After a fairly large amount of time I succeeded with that.
    To get an A though I need to also create a subclass of the PhoneDirectory called SortedPhoneDirectory with the only difference that the insert method automatically places the new Person in the right place in the list based on name. I have now succeded with that as well, but something is wrong, which brings me to my problem:
    When I access the methods in the PhoneDirectory class nothing happens - nothing at all. WHY :O:P
    Here are all my classes
    The class PhoneDirectory:
    The class PhoneDirectory is a Linked List containing Person objects.
    class PhoneDirectory
        private Node header;
        public PhoneDirectory()
            header = new Node(null );
        public void insert( Person o)
            header = new Node ( o, header);
        public void findWithName(String name)
            name = name.toLowerCase();
            Node runner = header;
            Person tmp;
            int i = 0;
            while(runner.element != null)
                tmp = get(i);
                if(tmp.getName().toLowerCase().contains(name))
                    System.out.println(tmp);
                runner = runner.next;
                i++;
        public void findWithAdress(String adress)
            adress = adress.toLowerCase();
            Node runner = header;
            Person tmp;
            int i = 0;
            while(runner.element != null)
                tmp = get(i);
                if(tmp.getAdress().toLowerCase().contains(adress))
                    System.out.println(tmp);
                runner = runner.next;
                i++;
        public void findWithPhone(String phone)
            phone = phone.toLowerCase();
            Node runner = header;
            Person tmp;
            int i = 0;
            while(runner.element != null)
                tmp = get(i);
                if(tmp.getPhoneNumber().toLowerCase().contains(phone))
                    System.out.println(tmp);
                runner = runner.next;
                i++;
        public void remove(int val)
            if(header == null)
                System.out.println("Its empty!");
            else if(val == 0)
                header = header.next;
            else
                Node runner = null;
                Node previous = null;
                runner = header.next;
                previous = header;
                int i = 1;
                while(runner.element != null)
                    if(i == val)
                        previous.next = runner.next;
                    previous = runner;
                    runner = runner.next;
                    i++;
        public void removeFirst()
            if(header == null)
                System.out.println("Its empty!");
            else
                header = header.next;
        public void print()
            Node tmp = header;
            while(tmp.element != null)
                System.out.println(tmp.element);
                tmp = tmp.next;
        public Person get(int val)
            int i = 0;
            boolean abort = false;
            Node tmp = header;
            while(val != i)
                tmp = tmp.next;
                i++;
                if(tmp.next == null)
                    abort = true;
                    break;
            if(abort)
                return null;
            else
                return tmp.element;
        public int size()
            int size = 0;
            Node tmp = header;
            while(tmp.element != null)
                tmp = tmp.next;
                size++;
            return size;
    }And here's the SortedPhoneDirectory:
    class SortedPhoneDirectory extends PhoneDirectory
        private Node header;
        public SortedPhoneDirectory()
            header = new Node(null);
        public void insert(Person o)
            Node newNode = new Node();
            newNode.element = o;
            if(header.element == null)
                header = newNode;
            else if(header.element.getName().compareToIgnoreCase(o.getName()) >= 0)
                newNode.next = header;
                header = newNode;
            else
                Node runner = header.next;
                Node previous = header;
                while(runner != null && runner.element.getName().compareToIgnoreCase(o.getName()) < 0)
                    previous = runner;
                    runner = runner.next;
                newNode.next = runner;
                previous.next = newNode;
    }The class Node that the linkedlist contains:
    class Node
        public Person element;
        public Node next;
          // Constructors
        public Node()
            next = null;
            element = null;
        public Node( Person theElement )
            this( theElement, null );
        public Node( Person theElement, Node n )
            element = theElement;
            next    = n;
    }The class Person that the Nodes are containing:
    class Person implements Comparable
        private String name;
        private String address;
        private String phone;
        public Person( String n, String ad, String p )
            name = n; address = ad; phone = p;
        public String toString( )
            return getName( ) + "\t"+ getAdress()+ "\t" + getPhoneNumber( );
        public final String getName( )
            return name;
        public final String getAdress( )
            return address;
        public final String getPhoneNumber( )
            return phone;
        public int compareTo( Object other)
            Person p=(Person)other;
            if(name.compareTo(p.getName())<0)
                return -1;
            else if(name.compareTo(p.getName())>0)
                return 1;
            else
                return 0;
    }And last my main program:
    public class telefonKatalog
        static String name;
        static String address;
        static String phone;
        public static void main(String[] args)
            SortedPhoneDirectory catalog =new SortedPhoneDirectory();
            catalog.insert(new Person("Donald","Paris", "10245630"));    //I just use these for testing
            catalog.insert(new Person("Jacob","London", "63294063"));
            catalog.insert(new Person("Max","Rome", "63215371"));
            for(;;)
                System.out.println("\n\nMain Menu\n____________________\n");
                System.out.println("1. Add a new person to the Phone Directory.");
                System.out.println("2. Find a person in the Phone Directory.");
                System.out.println("3. Remove a person from the Phone Directory");
                System.out.println("4. Print the whole Phone Directory");
                System.out.println("5. Exit.\n");
                char choice = Keyboard.readChar();
                switch(choice)
                    case '1':
                        System.out.println("\nAdd a new person to the Phone Directory\n______________________________________\n");
                        System.out.println("Name: ");
                        name = Keyboard.readString();
                        System.out.println("\nAdress: ");
                        address = Keyboard.readString();
                        System.out.println("\nPhone Number: ");
                        phone = Keyboard.readString();
                        catalog.insert(new Person(name, address, phone));
                        System.out.println("\nThe person has been added.\n");
                        break;
                    case '2':
                        System.out.println("\nFind a person in the Phone Directory.\n_________________________________\n");
                        System.out.println("1. Find by name.");
                        System.out.println("2. Find by address.");
                        System.out.println("3. Find by phone number\n");
                        choice = Keyboard.readChar();
                        switch(choice)
                            case '1':
                                System.out.println("\nFind by name.\n___________________\n");
                                System.out.println("Write the name of the person you are looking for:\n");
                                name = Keyboard.readString();
                                System.out.println();
                                catalog.findWithName(name);
                                break;
                            case '2':
                                System.out.println("\nFind by address.\n___________________\n");
                                System.out.println("Write the address:\n");
                                address = Keyboard.readString();
                                System.out.println();
                                catalog.findWithAdress(address);
                                break;
                            case '3':
                                System.out.println("\nFind by Phone Number.\n___________________\n");
                                System.out.println("Write the phone number:\n");
                                address = Keyboard.readString();
                                System.out.println();
                                catalog.findWithPhone(address);
                                break;
                            default:
                                System.out.println("\nUnvalid character!\n");
                                break;
                        break;
                    case '3':
                        System.out.println("\nRemove a person from the Phone Directory.\n____________________________________\n");
                        System.out.println("Write the name of the person you want to remove.\n");
                        String strChoice = Keyboard.readString();
                        boolean result = false;
                        for(int i = 0; i < catalog.size(); i++)
                            name = catalog.get(i).getName();
                            if(name.contains(strChoice))
                                catalog.remove(i);
                                System.out.println(name + " has been removed");
                                result = true;
                        if(!result)
                            System.out.println("There are no such person");
                        break;
                    case '4':
                        System.out.println("\nThe whole Phone Directory: \n_____________________________\n");
                        catalog.print();
                        System.out.println("\n_____________________________\n");
                        break;
                    case '5':
                        System.exit(0);
                    default:
                        System.out.println("\nUnvalid character!\n");
    }Its pretty long, sorry about that.. =)
    In the main program it all workes perfectly apart from the sorting if you change
    SortedPhoneDirectory catalog = new SortedPhoneDirectory(); into PhoneDirectory catalog = new PhoneDirectory();
    What is wrong about this code?? :O:(
    Edited by: YZF-R1 on 2008-maj-23 16:55

    YZF-R1 wrote:
    now thats just mean =( Why is that mean? I mean, you didn't learn something soon enough, and I am mean for not spoon feeding you the answer so that you can cheat by handing in work that is not your own? You already did that you just told us! This is called plagiarism and could get you expelled from school.
    I will sit down and learn all of that later when I have time, Sure. You should have learnt it sooner.
    but my deadline is tomorrow and its the last project of the course, so the teacher thought he would make up something extra. When I asked him if he could help me with my problem he couldn't even fix it, he thought everything looked as it was supposed to and so on.. :'( Come on, pleease :'(Christ, stop that!

  • Problems sorting larger sets of XMLType columns/tables

    Hi,
    Here's something I tried to wrap my head around:
    I'm using Oracle 11g r1 for Windows Server 2003.
    I've imported a fairly large set of XML files into a temporary XMLType table. Now
    I want to sort the contents of the table and put them into another table which
    uses a sequence to get primary keys (would be a longer story to explain, basically
    sorting by this non-XML primary key is super-fast as opposed to everything else
    I've tried, plus I need something unique):
    INSERT INTO realtable SELECT 0, object_value
    FROM tmptable ORDER BY extractValue(object_value, '/some/*/field');It works fine for a very small number of rows but when I tried with about 30000 rows,
    still not too much, two kinds of things can happen. Either, Oracle gobbles up a huge amount
    of memory (>1,5GB) until the statement breaks:
    ORA-04030: Zu wenig Prozessspeicher fⁿr Versuch 33292 Bytes zuzuweisen
    (callheap,kllcqgf:kllsltba)Or I get something like this:
    ORA-00600: Interner Fehlercode, Argumente: [kqludp2], [0x1F31EC94], [0], [], [], [], [], []I haven't wasted too much time looking into this. I tried storage options clob and binary xml
    for tmptable. Clob seems to induce the latter problem and binary xml the former but I haven't
    made further experiments.
    I can create a workaround from outside Oracle I think, so it's not serious however I'd would
    be interesting to know what happened or if there is a better way to do this.
    Thanks!

    Unfortunately, the problems are not reproducible in a meaningful way. All I can say is that once a statement will result in a kqludp2, it will always fail with the exactly same error message until I reinstall the database from scratch. On the other
    side, when I found a configuration that works, I could delete and rebuild/refill a table multiple times without the thing ever breaking.
    As the most recent example, after the latest trouble I deleted the database and changed my DDL scripts to the last configuration I wanted to try and broke the last time (several tables with two normal columns and an XMLType column each), everything worked like a breeze.
    I can file a TAR when I get a support ID from my employer, however I installed the database on a virtual machine (I should have mentioned that earlier) and Oracle doesn't officially support that configuration from what I know so I'll doubt they'll do anything about it. I've procured a physical computer now and try to reproduce any of the problems when I get to it.

  • Collections problem - Sorting object (not key) in treemap

    Hello everyone,
    I don't know if TreeMap is the right thing for what I want to do, but I haven't found anything better yet. What I want to do is have a tree map like that
    index -- value (Double)
    1        500
    2        450
    3        500   (Multiple value)
    4        123so I used a TreeMap, but what I want to do is get the indexes with the highest 5 values for example. Should I still use TreeMap? Is there a simple way to keep the values sorted rather than the keys (indices)?
    Thanx

    My problem is though, I want to sort them but then get the index of the minimum for example and with the LinkedList, I lose the mapping. With the treemap, I also cannot get the key (index) given an object, only the other way round. Is there a way to handle this?

  • Problem Sorting Photos in Slideshow

    I created a slideshow, putting the photos in the desired order. Now, for a reason I cannot understand, that order is completely reversed--front to back. When I go to View-Sort, everything is grayed out.
    Is there a keystroke that will reverse the order of the slides?

    Alpsteiner:
    Welcome to the Apple Discussions. Select all of the photos in the thumbnail tray at the top and then drag the first slide to the far right of the tray and wait for the blue slider to move to the far right and then release. That will reverse the order of the entire slideshow.
    Do you Twango?
    TIP: For insurance against the iPhoto database corruption that many users have experienced I recommend making a backup copy of the Library6.iPhoto database file and keep it current. If problems crop up where iPhoto suddenly can't see any photos or thinks there are no photos in the library, replacing the working Library6.iPhoto file with the backup will often get the library back. By keeping it current I mean backup after each import and/or any serious editing or work on books, slideshows, calendars, cards, etc. That insures that if a problem pops up and you do need to replace the database file, you'll retain all those efforts. It doesn't take long to make the backup and it's good insurance.
    I've written an Automator workflow application (requires Tiger), iPhoto dB File Backup, that will copy the selected Library6.iPhoto file from your iPhoto Library folder to the Pictures folder, replacing any previous version of it. You can download it at Toad's Cellar. Be sure to read the Read Me pdf file.

  • Problem sorting JTable with custom cell editor

    Greetings,
    I have created a JTable with a JComboBox as the cell editor for the first column. However, I couldn't simply set the default cell editor for the column to be a JComboBox, since the values within the list were different for each row. So instead, I implemented a custom cell editor that is basically just a hashtable of cell editors that allows you to have a different editor for each row in the table (based on the ideas in the EachRowEditor I've seen in some FAQs - see the code below). I also used a custom table model that is essentially like the JDBCAdapter in the Java examples that populates the table with a query to a database.
    The problem comes when I try to sort the table using the TableSorter and TableMap classes recommended in the Java Tutorials on JTables. All of the static (uneditable) columns in the JTable sort fine, but the custom cell editor column doesn't sort at all. I think that the problem is that the hashtable storing the cell editors never gets re-ordered, but I can't see a simple way to do that (how to know the old row index verses the new row index after a sort). I think that I could implement this manually, if I knew the old/new indexes...
    Here's the code I use to create the JTable:
    // Create the Table Model
    modelCRM = new ContactTableModel();
    // Create the Table Sorter
    sorterCRM = new TableSorter(modelCRM);
    // Create the table
    tblCRM = new JTable(sorterCRM);
    // Add the event listener for the sorter
    sorterCRM.addMouseListenerToHeaderInTable(tblCRM);
    Then, I populate the column for the custom cell editor like this:
    // Add the combo box for editing company
    TableColumn matchColumn = getTable().getColumn("Match");
    RowCellEditor rowEditor = new RowCellEditor();
    // loop through and build the combobox for each row
    for (int i = 0; i < getTable().getRowCount(); i++) {
    JComboBox cb = new JComboBox();
    cb.addItem("New");
    //... code to populate the combo box (removed for clarity)
    rowEditor.add(i,new DefaultCellEditor(cb, i))); //TF
    } // end for
    matchColumn.setCellEditor(rowEditor);
    Any ideas how to do this, or is there a better way to either sort the JTable or use a combobox with different values for each row? Please let me know if more code would help make this clearer...
    Thanks,
    Ted
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class RowCellEditor implements TableCellEditor
    protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    public RowCellEditor()
    editors = new Hashtable();
    defaultEditor = new DefaultCellEditor(new JTextField());
    public void add(int row, TableCellEditor editor)
    editors.put(new Integer(row), editor);
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    editor = (TableCellEditor) editors.get(new Integer(row));
    if (editor == null)
    editor = defaultEditor;
    return editor.getTableCellEditorComponent(table,
    value,
    isSelected,
    row,
    column);
    public Object getCellEditorValue() {
    return editor.getCellEditorValue();
    public boolean stopCellEditing() {
    return editor.stopCellEditing();
    public void cancelCellEditing() {
    editor.cancelCellEditing();
    public boolean isCellEditable(EventObject anEvent) {
    return true; //TF
    //return editor.isCellEditable(anEvent);
    public void addCellEditorListener(CellEditorListener l) {
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l) {
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent) {
    return editor.shouldSelectCell(anEvent);
    -------------------

    Well, I found a solution in another post
    (see http://forum.java.sun.com/thread.jsp?forum=57&thread=175984&message=953833#955064 for more details).
    Basically, I use the table sorter to translate the row index for the hashtable of my custom cell editors. I did this by adding this method to the sorter:
    // This method is used to get the correct row for the custom cell
    // editor (after the table has been sorted)
    public int translateRow(int sortedRowIndex)
    checkModel();
    return indexes[sortedRowIndex];
    } // end translateRow()
    Then, when I create the custom cell editor, I pass in a reference to the sorter so that when the getTableCellEditorComponent() method is called I can translate the row to the newly sorted row before returning the editor from the hashtable.

  • Problem Sorting Table

    Hi,
    I have used the TableMap.class, TableSorter.class, and check out the TableSorterDemo. I integrate the same code into my program but return this error when i click on the column head.
    'Sorter not informed of a change in model.'
    Does anyone know what this means? how can I resolve this problem?
    thanks.
    Alan

    Did you do a "find in files" for the string? If so, you would have seen the following method in TableSorter.java:
    public void checkModel() {
    if (indexes.length != model.getRowCount()) {
    System.err.println("Sorter not informed of a change in model.");
    The index in your sorter has more or fewer elements than your table model. Better look into any changes you made to your implementation of AbstractTableModel.

  • Problems sorting messages? (Mail.app, Lion, IMAP)

    I'm wondering if (how?) I'm the only person with this problem...
    I generally run with a window just open to my Inbox(-es).  That window is 2-columns, message list and message contents.  The hidden "Mailboxes" pane has several accounts under Inbox, most/all of which are IMAP servers.
    Here's the problem: The column heading for the list of messages reads "Sort by date".  However, the message list isn't sorted by date at all.  It appears that "Date" may be "date received", but I can't be certain of this.  In previous versions of Mail.app, there was a distinction between sorting by date of the message or the date received; in general I prefer the former.  But that doesn't seem to account for this:
    The options for this are Sorted by: Date, Ascending. 
    The interesting aspect of this is that if I choose one particular Inbox (i.e., the inbox from any account, rather than the "consolidated" listing), messages are sorted properly.  It's only when I have the view of all the inboxes (that is, the "Inbox" itself is selected, rather than any of the accounts under it) that sorting goes awry. 
    I do have lots of rules defined, moving certain messages from one place to another, and applying colors.  But this hadn't previously (nor would I expect it to) cause this issue. 
    Does anyone else have this problem, or any ideas on how to fix it?

    Apparently, I was either the only person to have an issue with this, or the only one bothered enough to write to the group!
    I do have a solution, however.
    From what I was able to tell, the issue was that the menu items for sorting, including the "Sort by" in the Mail window header bar and the View -> Sort by menu simply displayed "Date" as the option.
    Recalling the old trick of using the Option key while selecting a menu item, "Date" changed to "Date Sent".  It has not changed back to "Date"; now holding down Option changes it "Date Received", and the menu item continues to read "Date Sent", which is the desired behavior.
    Unfortunately, Mail was stuck in a state where both these indications simply said "Date"; I've now apparently changed this and the indicator reads properly (and the sort order is as expected).
    I hope if this bugs anyone else this explanation (?) will help.

  • Problems Sorting

    I have recently made a new template and am now using it for the first time. I seem to be unable to sort the table. I seem to be able to sort in any documents except those documents made using this new template. Any thoughts? Thanks!

    Thank you for your reply. After taking a break from the problem I realized that I had merged three cells in a column in order to add instructions for other users in the future. I deleted the text and unmerged the cells and all seems well now. I think. I will repost if that is not the case. Thanks again. This forum is a wonderful resource, especially for a newbe like me. I check it out daiy and have learned a great deal.

  • Problem Sorting Partially Filled Arrays

    I am having trouble sorting a partially filled array. What I want to have happen is have the user enter up to 50 numbers(int's only, 0's and negatives are allowed) and store the input in an array. Then sort the array, and display the sorted array from highest to lowest back to the user. The next step, which I haven't addressed yet is counting the number occurrences of each unique int and display that total to the user.
    I have the array fill working correctly. Where I am having problems is when i try and sort the array of user entered values. Instead of only sorting the entered values, it add's "0's" to the array and sorts and displays them as well.
    Here is what I want to have happen:
    The user enters 1 2 3 4 3 2 1, the output should be 4 3 3 2 2 1 1. But what is actually being output is 4 3 3 2 2 1 1 0 0 0 0 0 0 etc.(until the array is full).
    What am I doing wrong? If I display the contents of the array prior to sorting, it will only display the numbers entered, it does not add the extra 0's to fill the array. Any other suggestions on my code are welcome as well, always trying to get better at this, its tough teaching yourself form a book!
    And I have left some of my tracer variables in there as well.
    import java.util.Scanner;
    import java.util.Arrays;
    public class SortNumbers {
        //user can not enter more than 50 numbers to be sorted
        private static final int MAX_NUMBERS_ENTERED = 50;
        public static void main(String[] args) {
            // TODO code application logic here
            int[] sortThis = new int[MAX_NUMBERS_ENTERED];
            int numberUsed = 0;
            int count;
            System.out.println("Enter the numbers you would like to sort. Enter '1234' to stop. ");
            numberUsed = fillArray(sortThis);
            outputArray(sortThis, numberUsed);
        //this receives numbers from the user
        public static int fillArray(int[] a){
            Scanner keyboard = new Scanner(System.in);
            int next;
            int index = 0;
            next = keyboard.nextInt();
            while ((next != 1234) && (index < a.length)){
                a[index] = next;
                index++;
                next = keyboard.nextInt();
            return index;
        //this outputs the content of the array to the user
        public static void outputArray(int[] a, int numberUsed){
            //show the contents of the array
            System.out.println("The numbers you entered are: ");
            for (int i = 0; i < numberUsed; i++){
                System.out.print(a[i] + " ");
            System.out.println();
            System.out.println("***********");
            System.out.println("array length: " + a.length + ", " + "what array length should be: " + numberUsed);
            System.out.println("***********");
            //sort the array and show the sorted output
            Arrays.sort(a);
            for (int i = (MAX_NUMBERS_ENTERED - 1); i >= 0; i--){
                System.out.print(a[i] + " ");
    }

    This is what I've gotten so far...
                   //sort the array and show the sorted output
            Arrays.sort(a, 0, numberUsed);
            int qty = 1;
            //show the headers of the columns
            System.out.println("Num" + "  " + "Qty");
            //go through the numbers and output them along with their qty
            for (int i = (numberUsed - 1); i >= 0; i--){     
                if (a[i] != a[i+1]) {
                    System.out.println(a[i] + "    " + qty);
                    qty = 1;               
                else {
                    qty++;
            System.out.println();However, it's not working. If I only enter 1 instance of each number it works fine. However, if i enter multiple instances of a number, it doesn't work how it should.
    Any suggestions? Should I replace the if statement with a for loop?
    In the same problem, I can't figure out how to only display the entered number once and the number of times that it has been displayed. I think my two problems go hand in hand, if I figure the first one out, the second one should be easy.

  • Problem sorting by Artist in grid view using Itunes 8

    I have a lot of albums that contain various artist and i set up the info in each with the correct artist name and "various artist" as the album artist. In itunes 8 when i use grid view and use show by artist it displays by album artist putting all the albums by "various artist" in one grid. It's correct in list and cover flow view. How can i set the grid view to display by the artist of the song and not the album. (ex. Soundtrack from the motion picture Tropic Thunder: Display "U Can't Touch This" under MC Hammer instead of Various Artist)

    Actually, the grid view should be using the Album Artist tag. When the Album Artist tag was added in iTunes 7.0, the intent was to allow users to properly tag songs based on the artist and any guest artists. For instance, on Luther Vandross’ album +Give Me The Reason+ Track 6, “There’s Nothing Better Than Love” is a duet. Therefore, while the Artist tag for the rest of the tracks should be ‘Luther Vandross’, the correct tag content for Track 6 is ‘Luther Vandross duet with Greory Hines’. Without having ‘Luther Vandross’ in all the Album Artist tags for all 9 album tracks, iTunes would split the album as if there are two albums of the same name by different artists.
    The other situation are producer-driven albums like Quincy Jones’ +The Dude+ or +Back On The Block+ . These are not compilations, as you described, because the songs were produced for the albums and Quincy Jones, although not a performer on any of the tracks, is the album artist. The exception is soundtracks that are compilations of songs typically produced for a given film. Like the situation you describe, each track has a different artist, so by having ‘Quincy Jones’ in the Album Artist tag for each track, iTunes maintains the integrity of the album and keeps the tracks properly grouped.
    (Now if Apple would only acknowledge and fix the persistent bug that does not carry these grouping and sorting features over to the user’s music folder when they have enabled “Keep iTunes Music folder organized” in iTunes’ preferences.)
    The situation you are specifically referencing is that of tagging compilations—albums that consist of tracks by various artists where there is no actual album artist—but you have used the Album Artist tag effectively forcing iTunes to see them as single artist albums. I also tag compilations—e.g., Various Artists (Hip Hop), Various Artists (Jazz), Various Artists (R&B), Various Artists (Soundtrack), etc.—, so I understand what you have done. Unfortunately, the fix for forcing the grid view to recognize individual artists in compilations may require you to clear out the Album Artist tag on all of your compilation album tracks forcing iTunes to revert to the Artist tag in place of the Album Artist tag.
    What I would suggest is clearing the Album Artist tag of just one compilation and seeing what happens. If the album appears under “Unknown Artist”, or some other generic listing, in the grid view then iTunes only recognizes the Album Artist tag and I am at a loss as to what you could do. If it works as you hope, then you can go ahead an clear out the Album Artist field on the rest of your compilation albums.
    The downside of clearing the Album Artist field is that iTunes will revert to its pre-version 7 habits and break up the albums; that is, a compilation with 12 tracks by 12 different artists will appear in the various views as 12 different albums albeit with the same name and cover art. To keep the tracks properly grouped in other views, you will need to mark all of the tracks from the compilation albums as “Part of a compilation” in the info dialog.

  • After downloading photos from camera ... having problems sorting them ...

    Once I have downloaded an assortment of photos from my camera, I place them into separate folders according to the category I have named. In so doing, the photos are in the album, but remain in the import file which for some reason did not do so whenever I performed this task. What now occurs, is when I go to remove the photos in the imported file, it also removes them from the album.
    I am confused with what I am doing to cause this occurrence. I used to perform this task successfully when in the import screen without losing the photos once I placed them in their respective albums.
    Need help to sort myself out. I am a stickler for categorizing my photos according to the occasion. It makes it so easy to retrieve them whenever I want to send them to friends or to groups.
    Hope I can resolve my confusion in what I am doing wrong.
    Thanks!
    Message was edited by: kananaskis
    I used to be able to sort my imported photos without the aforementioned occurrence. It appears to occur using a new camera.

    Thank you, Terence, for the information. I'm going to mull this over because what you have mentioned is rather abstract to my diminishing grey cells. When I returned to iPhoto, in the Photos' List, the photos I had categorized were in tact and none of the other photos were included.
    Much for me to consider when importing photos and my placing them into folders but forget about 'trashing' what is in the Import file, because as you say, this is only a shortcut.
    Again, thanks for shedding some light on my dimly lit understanding of iPhoto and its importing photos.

Maybe you are looking for