Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 17 of 17

Thread: Sorting issues.

  1. #1
    Member
    Join Date
    Apr 2012
    Posts
    60
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Sorting issues.

    This program is supposed to take a lit of objects, and sort them in different ways. Along with that, the assignment requires us to use different algorithms for some of them, so that is why my methods do not all look the same. The method in question is sortName(), which obviously is supposed to sort by name. It uses the same algorithm as sortID(), which works fine. The error - "java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
    at java.util.ArrayList.rangeCheck(ArrayList.java:604)
    at java.util.ArrayList.get(ArrayList.java:382)
    at TestItem.sortName(TestItem.java:79)
    at TestItem.main(TestItem.java:148)"

    occurs at the line "a.add(i, a.get(posmax));
    Which shouldnt throw this exception, because the line before it removes i, making the List 1 smaller, so therefore it should have room. Take a look and throw me some solutions! Thanks!

    import java.text.*;
    import java.util.*;
    public class TestItem
    {
    private static List<Item> hardware = new ArrayList<Item>();
     
        public static void printInventory(List<Item> a)
        {
            System.out.println("itemID    itemName     Stock    Price");
            System.out.println("------------------------------------------");
     
            for(Item i : a)
            {
                System.out.println(i);
            }
            System.out.println();
     
        }
     
        public static void sortID(List<Item> a)
        {
            int i;
            int k;
            int posmax;
            Item temp;
            for ( i = a.size() - 1 ; i >= 0 ; i-- )
            {
                posmax = 0;
     
                Item gmaxobj = a.get(posmax);
                 int gmax = Integer.parseInt(gmaxobj.getID());
                for ( k = 0 ; k <= i ; k++ )
                {
                    Item gobj = a.get(k);
                    int g = Integer.parseInt(gobj.getID());
                    if (g > gmax)
                     posmax = k;
             }
             temp = a.get(i);
             a.remove(i);
             a.add(i, a.get(posmax));
             a.remove(posmax);
             a.add(posmax, temp);
            }
     
            System.out.println("Sorting by ID..");
            System.out.println();
            printInventory(hardware);
            System.out.println();
        }
     
            public static void sortName(List<Item> a)
            {
                      int i;
                    int k;
                    int posmax;
                    Item temp;
                    for ( i = a.size() - 1 ; i >= 0 ; i-- )
                    {
                        posmax = 0;
     
                        Item gmax = a.get(posmax);
     
                        for ( k = 0 ; k <= i ; k++ )
                        {
                            Item g = a.get(k);
                            if (g.getName().compareTo(gmax.getName()) > 0 )
                         posmax = k;
                     }
                     temp = a.get(i);
                     a.remove(i);
                     a.add(i, a.get(posmax));
                     a.remove(posmax);
                     a.add(posmax, temp);
                    }
     
                    System.out.println("Sorting by Name..");
                    System.out.println();
                    printInventory(hardware);
                    System.out.println();
            }
     
     
     
     
            public static void sortInStore(List<Item> a)
        {
            int i;
            int k;
            int posmax;
            Item temp;
            for ( i = a.size() - 1 ; i >= 0 ; i-- )
            {
                posmax = 0;
     
                Item gmax = a.get(posmax);
     
                for ( k = 0 ; k <= i ; k++ )
                {
                    Item g = a.get(k);
                    if (g.getStock() > gmax.getStock() )
                 posmax = k;
             }
             temp = a.get(i);
             a.remove(i);
             a.add(i, a.get(posmax));
             a.remove(posmax);
             a.add(posmax, temp);
            }
     
            System.out.println("Sorting by Stock..");
            System.out.println();
            printInventory(hardware);
            System.out.println();
        }
     
     
            public static void sortPrice(List<Item> a)
        {
     
     
        }
     
     
     
     
       public static void main(String [] args)
       {
           hardware.add(0, new Item("100", "Air Filters", 200, 10.5));
           hardware.add(1, new Item("101", "Door Knobs", 60, 21.5));
           hardware.add(2, new Item("102", "Hammers", 90, 9.99));
           hardware.add(3, new Item("103", "Levels", 80, 19.99));
           hardware.add(4, new Item("104", "Ceiling Fans", 100, 59));
           hardware.add(5, new Item("105", "Wrench Sets", 55, 80));
     
           printInventory(hardware);
           sortInStore(hardware);
     
           sortID(hardware);
     
           sortName(hardware);
     
     
     
        }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorting issues.

    The error - "java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
    at java.util.ArrayList.rangeCheck(ArrayList.java:604)
    at TestItem.sortName(TestItem.java:79)
    On line on 79 the index you are using went past the end of the array. Check your logic to keep the index in bounds.
    Remember the indexes for arrays start at 0 and go to the array length-1.

    Print out the size of the arraylist and the value of the index: posmax if you need to see what the computer is seeing.
    Last edited by Norm; April 29th, 2012 at 06:17 AM.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    Saintroi (April 30th, 2012)

  4. #3
    Member
    Join Date
    Jan 2012
    Location
    Hellas
    Posts
    284
    Thanks
    11
    Thanked 59 Times in 57 Posts

    Default Re: Sorting issues.

    Hello Santroi!
    a.remove(i);
    a.add(i, a.get(posmax));
    You are removing the element in the i-th position of your list and then you try to add in it a.get(posmax). But from your inner for loop, posmax can be equal to i. I would definitely recommend you follow Norm's suggestion to see what's going on with the indexes.
    Hope it helps.

  5. The Following User Says Thank You to andreas90 For This Useful Post:

    Saintroi (April 30th, 2012)

  6. #4
    Member
    Join Date
    Apr 2012
    Posts
    60
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Sorting issues.

    Okay, making the k <= i just k < i seems to have fixed it, but I see more problems with it. I will give you both classes on this post, and if you run it you will see that 2 of the Items that are printed are printed differently than the rest and I cant figure out why. If you have a fix for that please let me know. Also, the sortName method is sorting the names strangely. I need them in alphabetical order, so if anyone can give me a new method to try for that, it would be appreciated. I was going off of an example they had given us, but it was using an array of ints. It has to be an "Insertion" sort, which involves creating an empty copy of the array you are sorting. Then, one by one, taking values from the array you want to sort and insert them into the empty array.

    Thanks for any help you can offer!

    Item Class.

    import java.text.*;
    import java.util.*;
     
    public class Item
    {
      private String itemID, itemName;
      private int inStore;
      private double price;
      private DecimalFormat df = new DecimalFormat("#.##");
        public Item (String id, String name, int stock, double cost)
        {
        itemID = id;
        itemName = name;
        inStore = stock;
        price = cost;
     
       }
     
       public String getID()
       {
           return itemID;
        }
     
           public String getName()
        {
           return itemName;
        }
     
           public int getStock()
        {
           return inStore;
        }
     
           public double getPrice()
        { 
           return price;
        }
     
        public String toString()
        {
           return " " + itemID + "\t" + itemName + "\t" + inStore + " \t" + "$" + df.format(price);
        }
    }

    TestItem Class.

    import java.text.*;
    import java.util.*;
    public class TestItem
    {
    private static List<Item> hardware = new ArrayList<Item>();
     
        public static void printInventory(List<Item> a)
        {
            System.out.println("itemID    itemName     Stock    Price");
            System.out.println("------------------------------------------");
     
            for(Item i : a)
            {
                System.out.println(i);
            }
            System.out.println();
     
        }
     
        public static void sortID(List<Item> a)
        {
            int i;
            int k;
            int posmax;
            Item temp;
            for ( i = a.size() - 1 ; i >= 0 ; i-- )
            {
                posmax = 0;
     
                Item gmaxobj = a.get(posmax);
                 int gmax = Integer.parseInt(gmaxobj.getID());
                for ( k = 0 ; k <= i ; k++ )
                {
                    Item gobj = a.get(k);
                    int g = Integer.parseInt(gobj.getID());
                    if (g > gmax)
                     posmax = k;
             }
             temp = a.get(i);
             a.remove(i);
             a.add(i, a.get(posmax));
             a.remove(posmax);
             a.add(posmax, temp);
            }
     
            System.out.println("Sorting by ID..");
            System.out.println();
            printInventory(hardware);
            System.out.println();
        }
     
            public static void sortName(List<Item> a)
            {
                      int i;
                    int k;
                    int posmax;
                    Item temp;
                    for ( i = a.size() - 1 ; i >= 0 ; i-- )
                    {
                        posmax = 0;
     
                        Item gmax = a.get(posmax);
     
                        for ( k = 0 ; k < i ; k++ )
                        {
                            Item g = a.get(k);
                            if (g.getName().compareTo(gmax.getName()) > 0 )
                         posmax = k;
                     }
                     temp = a.get(i);
                     a.remove(i);
                     a.add(i, a.get(posmax));
                     a.remove(posmax);
                     a.add(posmax, temp);
                    }
     
                    System.out.println("Sorting by Name..");
                    System.out.println();
                    printInventory(hardware);
                    System.out.println();
            }
     
     
     
     
            public static void sortInStore(List<Item> a)
        {
            int i;
            int k;
            int posmax;
            Item temp;
            for ( i = a.size() - 1 ; i >= 0 ; i-- )
            {
                posmax = 0;
     
                Item gmax = a.get(posmax);
     
                for ( k = 0 ; k <= i ; k++ )
                {
                    Item g = a.get(k);
                    if (g.getStock() > gmax.getStock() )
                 posmax = k;
             }
             temp = a.get(i);
             a.remove(i);
             a.add(i, a.get(posmax));
             a.remove(posmax);
             a.add(posmax, temp);
            }
     
            System.out.println("Sorting by Stock..");
            System.out.println();
            printInventory(hardware);
            System.out.println();
        }
     
     
            public static void sortPrice(List<Item> a)
        {
     
     
        }
     
     
     
     
       public static void main(String [] args)
       {
           hardware.add(0, new Item("100", "Air Filters", 200, 10.5));
           hardware.add(1, new Item("101", "Door Knobs", 60, 21.5));
           hardware.add(2, new Item("102", "Hammers", 90, 9.99));
           hardware.add(3, new Item("103", "Levels", 80, 19.99));
           hardware.add(4, new Item("104", "Ceiling Fans", 100, 59));
           hardware.add(5, new Item("105", "Wrench Sets", 55, 80));
     
           printInventory(hardware);
           sortInStore(hardware);
     
           sortID(hardware);
     
           sortName(hardware);
     
     
     
        }
    }

  7. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorting issues.

    2 of the Items that are printed are printed differently than the rest
    Please post the output that shows what you are talking about
    If you don't understand my answer, don't ignore it, ask a question.

  8. The Following User Says Thank You to Norm For This Useful Post:

    Saintroi (May 2nd, 2012)

  9. #6
    Member
    Join Date
    Apr 2012
    Posts
    60
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Sorting issues.

    out.jpg

    That help?

  10. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorting issues.

    Post the output as text that can be copied and pasted into other posts. Can't do that with images.
    Also can you add comments the parts you are talking about.
    If you don't understand my answer, don't ignore it, ask a question.

  11. The Following User Says Thank You to Norm For This Useful Post:

    Saintroi (May 2nd, 2012)

  12. #8
    Member
    Join Date
    Jan 2012
    Location
    Hellas
    Posts
    284
    Thanks
    11
    Thanked 59 Times in 57 Posts

    Default Re: Sorting issues.

    I tried your code and changed a little the Item's toString() but didn't find what is causing this formatting. The only thing I noticed is that this is happening if the name's length is less than 8. With a name's length >= 8, the formatting works.
    Hope this helps somebody else find the bug (I'm very curious to know what's the bug).

  13. The Following User Says Thank You to andreas90 For This Useful Post:

    Saintroi (May 2nd, 2012)

  14. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorting issues.

    It's not a bug. Its the way tab characters work. tabs are NOT a reliable way to format output unless you can set where they are defined to be. I don't know how to set tabs for the console.

    If you pad the Strings to a standard length, you will have better control over where the columns line up.
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following 2 Users Say Thank You to Norm For This Useful Post:

    andreas90 (April 30th, 2012), Saintroi (May 2nd, 2012)

  16. #10
    Member
    Join Date
    Apr 2012
    Posts
    60
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Sorting issues.

    Yeah I may just make the names to all be at least 8. It seems like the most viable choice. I only do it this way because I am required to use toString in my assignment. Usually I would just use printf. Any ideas on changing the sortName method though? as of right now it sorts by name, but I dont know exactly what it means by that. Its not in alphabetical order, which is what i'd like it to be. But the method has to involve putting them in order into a new List.

  17. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorting issues.

    Try debugging the sort method by adding println statements to it that print out the values of the variables and shows the execution flow. The print out will show you what the computer sees and help yo understand what the cde is doing.
    If you don't understand my answer, don't ignore it, ask a question.

  18. The Following User Says Thank You to Norm For This Useful Post:

    Saintroi (May 2nd, 2012)

  19. #12
    Member
    Join Date
    Apr 2012
    Posts
    60
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Sorting issues.

    I did that and I dont understand why its seeing what its seeing. When two strings are compared using compareTo, is it based on alphabetical or what? Because if not then this method wont do what I want it to anyway.

  20. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorting issues.

    When two strings are compared using compareTo, is it based on alphabetical
    Add printlns to show what the args to compareTo() are and what it returns.
    Or write some simple test code like this with several different values: System.out.println("asdd".compareTo("xxx"));
    If you don't understand my answer, don't ignore it, ask a question.

  21. The Following User Says Thank You to Norm For This Useful Post:

    Saintroi (May 2nd, 2012)

  22. #14
    Member
    Join Date
    Apr 2012
    Posts
    60
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Sorting issues.

    Well ive given up trying to do different sorts, so i'll just make them all selection. My problem is, 2 of my selection sorts are not working now. The sortName() is still printing wrong, which is probably due to the compareTo method, but I cant find how. And the sortPrice, a new method, is sorting wrong and I dont know why. I'll post my new code to let you see all the changes and see if you can let me know whats going on.

    import java.text.*;
    import java.util.*;
    public class TestItem
    {
    private static List<Item> hardware = new ArrayList<Item>();
     
        public static void printInventory(List<Item> a)
        {
            System.out.println("itemID    itemName     Stock    Price");
            System.out.println("------------------------------------------");
     
            for(Item i : a)
            {
                System.out.println(i);
            }
            System.out.println();
     
        }
     
        public static void sortID(List<Item> a)
        {
            int i;
            int k;
            int posmax;
            Item temp;
            for ( i = a.size() - 1 ; i >= 0 ; i-- )
            {
                posmax = 0;
     
                Item gmaxobj = a.get(posmax);
                 int gmax = Integer.parseInt(gmaxobj.getID());
                for ( k = 0 ; k <= i ; k++ )
                {
                    Item gobj = a.get(k);
                    int g = Integer.parseInt(gobj.getID());
                    if (g > gmax)
                     posmax = k;
             }
             temp = a.get(i);
             a.remove(i);
             a.add(i, a.get(posmax));
             a.remove(posmax);
             a.add(posmax, temp);
            }
     
            System.out.println("Sorting by ID..");
            System.out.println();
            printInventory(hardware);
            System.out.println();
        }
     
            public static void sortName(List<Item> a)
            {
                     int i;
                int k;
                int posmax;
                Item temp;
                for ( i = a.size() - 1 ; i >= 0 ; i-- )
                {
                    posmax = 0;
     
                    Item gmax = a.get(posmax);
     
                    for ( k = 0 ; k <= i ; k++ )
                    {
                        Item g = a.get(k);
                        if (gmax.getName().compareTo(g.getName()) < 0)
                     posmax = k;
                 }
                 temp = a.get(i);
                 a.set(i, a.get(posmax));
                 a.set(posmax, temp);
                }
     
                System.out.println("Sorting by Name..");
                System.out.println();
                printInventory(hardware);
                System.out.println();
              }
     
     
            public static void sortInStore(List<Item> a)
        {
            int i;
            int k;
            int posmax;
            Item temp;
            for ( i = a.size() - 1 ; i >= 0 ; i-- )
            {
                posmax = 0;
     
                Item gmax = a.get(posmax);
     
                for ( k = 0 ; k <= i ; k++ )
                {
                    Item g = a.get(k);
                    if (g.getStock() > gmax.getStock() )
                 posmax = k;
             }
             temp = a.get(i);
             a.remove(i);
             a.add(i, a.get(posmax));
             a.remove(posmax);
             a.add(posmax, temp);
            }
     
            System.out.println("Sorting by Stock..");
            System.out.println();
            printInventory(hardware);
            System.out.println();
        }
     
     
            public static void sortPrice(List<Item> a)
        {
            int i;
            int k;
            int posmax;
            Item temp;
            for ( i = a.size() - 1 ; i >= 0 ; i-- )
            {
                posmax = 0;
     
                Item gmax = a.get(posmax);
     
                for ( k = 0 ; k <= i ; k++ )
                {
                    Item g = a.get(k);
                    if (g.getPrice() > gmax.getPrice() )
                 posmax = k;
             }
             temp = a.get(i);
             a.set(i, a.get(posmax));
             a.set(posmax, temp);
            }
     
            System.out.println("Sorting by Price..");
            System.out.println();
            printInventory(hardware);
            System.out.println();
     
       }  
     
     
       public static void main(String [] args)
       {
           hardware.add(0, new Item("100", "Air Filters", 200, 10.5));
           hardware.add(1, new Item("101", "Door Knobs", 60, 21.5));
           hardware.add(2, new Item("102", "Sledge Hammers", 90, 9.99));
           hardware.add(3, new Item("103", "Laser Levels", 80, 19.99));
           hardware.add(4, new Item("104", "Ceiling Fans", 100, 59));
           hardware.add(5, new Item("105", "Wrench Sets", 55, 80));
     
           printInventory(hardware);
           sortInStore(hardware);
     
           sortID(hardware);
     
           sortName(hardware);
     
           //sortPrice(hardware, (int)Math.floor(findHigh(hardware)), (int)Math.floor(findLow(hardware)));
     
           sortPrice(hardware);
        }
    }

    import java.text.*;
    import java.util.*;
     
    public class Item
    {
      private String itemID, itemName;
      private int inStore;
      private double price;
      private DecimalFormat df = new DecimalFormat("#.##");
        public Item (String id, String name, int stock, double cost)
        {
        itemID = id;
        itemName = name;
        inStore = stock;
        price = cost;
     
       }
     
       public String getID()
       {
           return itemID;
        }
     
           public String getName()
        {
           return itemName;
        }
     
           public int getStock()
        {
           return inStore;
        }
     
           public double getPrice()
        { 
           return price;
        }
     
        public String toString()
        {
           return " " + itemID + "\t" + itemName + "\t" + inStore + " \t" + "$" + df.format(price);
        }
    }

    Basically, i'm so tired and confused by what ive done with this, that i'm almost ready to wipe it and start over. Just treat it like its a brand new question, even though the code hasnt drastically changed.

  23. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorting issues.

    know whats going on.
    Adding printlns will show you what is going on. If you have worked out the logic with paper an pencil, the print outs will show you what the code is doing so you can understand what the computer sees and change the code so it does what your design says it should do.

    I have no idea what the code in your program is supposed to do. There are no comments saying what the logic is and how each of the methods is supposed to work. How can anyone look at the code and see if it is following the design?
    Last edited by Norm; May 2nd, 2012 at 06:58 PM.
    If you don't understand my answer, don't ignore it, ask a question.

  24. The Following User Says Thank You to Norm For This Useful Post:

    Saintroi (May 2nd, 2012)

  25. #16
    Member
    Join Date
    Apr 2012
    Posts
    60
    Thanks
    25
    Thanked 0 Times in 0 Posts

    Default Re: Sorting issues.

    I guess you have a point. But I mean its simple, each method sorts the Items in the array differently according to the name. sortName() will obviously sort them by their name, ect.

    As to each thing, I cant say i'm positive as to what each line of code is supposed to do, most of it got pulled from some instructions and edited based on what I learned from looking stuff up, and it worked for 2 methods.

    But, I am sorry for my being hasty, I was frustrated and looking for an easy fix, which I found after a little work. The line "Item gmax = a.get(posmax);" needed to be inside the second for loop for it to work.
    Thanks for all your help.

  26. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Sorting issues.

    I made a slight change to the data and the order of the sorts and now none of them work.

       public static void main(String [] args)    {
           hardware.add( new Item("100", "Air Filters",  200, 10.5));
           hardware.add( new Item("101", "Door Knobs",    60, 21.5));
           hardware.add( new Item("105", "Wrench Sets",   55, 80));  //<<< moved this here 
           hardware.add( new Item("102", "Sledge Hammers",90, 9.99));
           hardware.add( new Item("103", "Laser Levels",  80, 19.99));
           hardware.add( new Item("104", "Ceiling Fans", 100, 59));
     
           printInventory(hardware);
     //      sortInStore(hardware); // Removing this causes next method to fail 
           sortID(hardware);
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. [SOLVED] Memory issues..?
    By Saintroi in forum What's Wrong With My Code?
    Replies: 10
    Last Post: April 24th, 2012, 10:31 PM
  2. Jlabel issues
    By Wadashe in forum Java Theory & Questions
    Replies: 2
    Last Post: February 27th, 2012, 02:39 PM
  3. Noobie issues?
    By sukuiichuu in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 3rd, 2011, 05:10 AM
  4. [SOLVED] Image issues
    By Toll in forum Java Theory & Questions
    Replies: 7
    Last Post: May 19th, 2011, 09:43 PM
  5. Triangle issues
    By FrEaK in forum What's Wrong With My Code?
    Replies: 0
    Last Post: February 24th, 2010, 08:49 AM