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 18 of 18

Thread: Java IndexOutOfBound

  1. #1
    Member
    Join Date
    Dec 2012
    Posts
    127
    My Mood
    Angelic
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Java IndexOutOfBound

    Could someone help me with fixing this indexoutofbound error? The error is occuring at
    "s += catalog.get(i).toString() + "," + catalog.get(i).getSKU() + ": " + b.getContents().get(i)+ "\n" ;"

    java.lang.IndexOutOfBoundsExceptions: Index 1 Size 1 - Is the error I am getting. Thanks

    import java.util.*;
    public class Media
    {   
        public static ArrayList<MusicMedia> MakeMusicCatalog(int size)
        {
            String[]titles = 
                {
                    "Greatest Hits volume 1", "Greatest Hits Volume 2",
                    "The Best of", "Love Songs",
                    "The Early Years", "The Later Years"
                };
            String [] artists = 
                {
                    "Michael Jackson", "Eminem",
                    "The Beatles", "Shania Twain",
                    "Limp Bizkit"
                };
            ArrayList<MusicMedia> a = new ArrayList<MusicMedia>();
            Random rn = new Random();
            for (int i = 0 ; i < size; i++)
            {
                MusicMedia m ;
     
                int mediatype = rn.nextInt(3);
                String title = titles[rn.nextInt(titles.length)];
                String artist = artists[rn.nextInt(artists.length)];
                String sku = "1234-"+ i;
                if(mediatype == 0 )
                    m = new CompactDisk (title, artist, sku);
                else if(mediatype == 1)
                    m = new DigitalVideoDisk(title,artist,sku);
                else 
                    m = new CassetteTape(title,artist,sku);
     
                a.add(m);
                }
                return a;
            }
     
        public static String lookupMedia(ArrayList<MusicMedia> catalog, String sku)
        {   
            for(MusicMedia m : catalog)
            {
                if(m.getSKU().equalsIgnoreCase(sku))
                {
                    return sku;
                }
            }
            return "SKU not in catalog";
        }
     
        public static String detailedInventory(ArrayList<MusicMedia> catalog, ArrayList<Bin> warehouse)
        {
            String s = "";
            for(Bin b : warehouse)
            {
                s += "Bin " + b.getName()+ ":\n";
                for(int i = 0 ; i < (warehouse.size()); i++)
                {
                    s += catalog.get(i).toString() + "," + catalog.get(i).getSKU() + ": " + b.getContents().get(i)+ "\n" ;
                }
                s += "\n";
            }
            return s;
        }
     
        public static void main(String[]args)
        {
          ArrayList<MusicMedia> catalog = MakeMusicCatalog( 10 );
          ArrayList<Bin> warehouse = new ArrayList<Bin>();
          Bin a = new Bin( "A" );
          Bin b = new Bin( "B" );
          warehouse.add( a );
          warehouse.add( b );
          a.add( new BinItem( "1234-0", 500 ) );
          a.add( new BinItem( "1234-1", 25 ) );
          a.add( new BinItem( "1234-2", 7720 ) );
          b.add( new BinItem( "1234-3", 1000 ) );
          System.out.println( detailedInventory( catalog, warehouse));
     
        }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,420
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Java IndexOutOfBound

    java.lang.IndexOutOfBoundsExceptions: Index 1 Size 1
    If the array has a size of 1 then the maximum index is 0.

    Check the logic to make sure the index does not go past the array length-1
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Dec 2012
    Posts
    127
    My Mood
    Angelic
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Java IndexOutOfBound

    That what I was thinking too. Since the size of warehouse is only 4, the maximum index would be 3. I figured the error is at "for(Bin b : warehouse)" since warehouse is 4 and it would result in the inner for loop running 4 time but the index of warehouse should be 3, am I correct? Thanks

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,420
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Java IndexOutOfBound

    Which get() is causing the error? Look at the size of the collections connected to the get() methods being called.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Dec 2012
    Posts
    127
    My Mood
    Angelic
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Java IndexOutOfBound

    "b.getContents().get(i)" is causing the error because only 4 ArrayList is created but the for loop is calling for < catalog.size() which is 10.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,420
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Java IndexOutOfBound

    It doesn't make sense to use a index that is past the end. The code needs to be changed so the index does not go past the end.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Dec 2012
    Posts
    127
    My Mood
    Angelic
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Java IndexOutOfBound

    I edited the code a little and here is the new code
    import java.util.*;
    public class Media
    {   
        public static ArrayList<MusicMedia> MakeMusicCatalog(int size)
        {
            String[]titles = 
                {
                    "Greatest Hits volume 1", "Greatest Hits Volume 2",
                    "The Best of", "Love Songs",
                    "The Early Years", "The Later Years"
                };
            String [] artists = 
                {
                    "Michael Jackson", "Eminem",
                    "The Beatles", "Shania Twain",
                    "Limp Bizkit"
                };
            ArrayList<MusicMedia> a = new ArrayList<MusicMedia>();
            Random rn = new Random();
            for (int i = 0 ; i < size; i++)
            {
                MusicMedia m ;
     
                int mediatype = rn.nextInt(3);
                String title = titles[rn.nextInt(titles.length)];
                String artist = artists[rn.nextInt(artists.length)];
                String sku = "1234-"+ i;
                if(mediatype == 0 )
                    m = new CompactDisk (title, artist, sku);
                else if(mediatype == 1)
                    m = new DigitalVideoDisk(title,artist,sku);
                else 
                    m = new CassetteTape(title,artist,sku);
     
                a.add(m);
                }
                return a;
            }
     
        public static String lookupMedia(ArrayList<MusicMedia> catalog, String sku)
        {   
            for(MusicMedia m : catalog)
            {
                if(m.getSKU().equalsIgnoreCase(sku))
                {
                    return sku;
                }
            }
            return "SKU not in catalog";
        }
     
        public static String detailedInventory(ArrayList<MusicMedia> catalog, ArrayList<Bin> warehouse)
        {
            String s = "";
            for(int i = 0  ; i < warehouse.size();i++)
            {
                s += "Bin " + warehouse.get(i).getName()+ ":\n";
                s += catalog.get(i) + "," + warehouse.get(i).getContents()+ "\n" ;
                s += "\n";
            }
            return s;
    }   
     
     
     
        public static void main(String[]args)
        {
          ArrayList<MusicMedia> catalog = MakeMusicCatalog( 10 );
          ArrayList<Bin> warehouse = new ArrayList<Bin>();
          Bin a = new Bin( "A" );
          Bin b = new Bin( "B" );
          warehouse.add( a );
          warehouse.add( b );
          a.add( new BinItem( "1234-0", 500 ) );
          a.add( new BinItem( "1234-1", 25 ) );
          a.add( new BinItem( "1234-2", 7720 ) );
          b.add( new BinItem( "1234-3", 1000 ) );
          System.out.println( detailedInventory( catalog, warehouse));
     
        }
    }

    import java.util.*;
    public class Bin
    {
        private String myName;
        private ArrayList<BinItem> myContents ;
     
        public Bin(String name)
        {
            myName = name;
            myContents =  new ArrayList<BinItem>();
        }
     
        public String getName()
        {
            return myName;
        }
     
        public void add(BinItem b)
        {
              myContents.add(b);
        }
     
            public ArrayList<BinItem> getContents()
        {
            return myContents;
        }
        public String toString()
        {
            String s = "Bin "+ myName + ":\n";
            for (BinItem b : myContents)
                s += b + "\n";
     
            return s;
        }
    }

    The program is printing "Bin A:
    DVD - The Best of (The Beatles),[SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]

    Bin B:
    Cassette - The Later Years (Michael Jackson),[SKU 1234-3: 1000]"

    -It suppose to print 3 song for Bin A but my program is only printing 1 song and the ID of 2 of the other song. May i get a lead on to where is the error? Thanks

    Something like this
    "Bin A:
    CD - The Later Years (Shania Twain), SKU 1234-0: 500
    Cassette - Greatest Hits Volume 2 (The Beatles), SKU 1234-1: 25
    Cassette - Greatest Hits Volume 1 (Shania Twain), SKU 1234-2: 7720
    Bin B:
    Cassette - Greatest Hits Volume 2 (Michael Jackson), SKU 1234-3: 1000"

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,420
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Java IndexOutOfBound

    Try debugging the code by adding printlns that print out the contents of the collections and variables so you can see what the computer sees when it executes the program.
    suppose to print 3 song for Bin A but my program is only printing 1
    Print the contents of Bin A every time a song is added to it to follow how many songs Bin A holds.


    Where is the loop that goes through the contents of each Bin? Add some printlns to track the looping.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Dec 2012
    Posts
    127
    My Mood
    Angelic
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Java IndexOutOfBound

    I tested it and the catalog.get() is working fine but it seem the warehouse arraylist only have the size of 2 for some reason. Could you check in the Bin class if I wrote the methods to add to ArrayList and setting it to a get method correctly? Thanks
       public void add(BinItem b)
        {
              myContents.add(b);
        }
     
            public ArrayList<BinItem> getContents()
        {
            return myContents;
        }

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,420
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Java IndexOutOfBound

    check in the Bin class if I wrote the methods to add to ArrayList and setting it to a get method correctly
    You can do that by adding some calls to the println() method to print out the contents of the ArrayList every time something is added to it. For example, Add this to the add() method and the getContents:
    System.out.println("add() mC= "+ myContents);
    System.out.println("getContents() mC= "+ myContents);
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    Dec 2012
    Posts
    127
    My Mood
    Angelic
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Java IndexOutOfBound

    Sorry to keep bothering you ,Norm. But after modifying my code with what I know, I still can't get it to print 3 song for Bin A instead of 1 song. May I get some more hints? Thanks

    The direction I got for this part of the code was
    "Use a for-each loop to cycle through all the bins in the warehouse.

    ● For each bin, extend s by the String "Bin " followed by the name of
    the bin, followed by a colon and \n (to start a new line).

    ● Cycle through all the bin items in the current bin, for each one
    extending s by a new line of text that begins with the result of looking
    up the current bin item’s SKU in the input catalog, and continues with
    a comma followed by the String representation of the bin item."

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,420
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Java IndexOutOfBound

    can't get it to print 3 song for Bin A instead of 1 song.
    Continue debugging the code by adding more printlns. If you print out the contents of the arraylists every time you add something to the arraylist, what is printed out will show you what is in the arraylist. If there is only one item in the list every time something is added, you need to find out what happened to what was added the last time add() was called. Perhaps the code is creating a new arraylist every time so that what was added the last time is lost when the new arraylist was created.

    Where is the loop that goes through the contents of each Bin? Add some printlns to track the looping.

    Copy what is printed out by these printlns and paste it here.

    I'm done for tonight. Back tomorrow.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Dec 2012
    Posts
    127
    My Mood
    Angelic
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Java IndexOutOfBound

    Thanks for the help yesterday, Norm. I managed to change the code to print out 3 different song for Bin A but it is using the first song from Bin A for Bin B instead of another random song. I believe this is cause by the loop only getting 3 songs because of the index.
            String s = "";
     
            for (Bin b : warehouse) 
            {   s += "Bin "+b.getName()+"\n";
                for(int i = 0  ; i < b.getContents().size()+1;i++)
                {
                    s += b.catalog.get(i).toString()+"\n";
                }
                s+= "\n";
                    }
            return s;

    This is what it printing
    "Bin A
    DVD - The Later Years (Eminem)
    DVD - Greatest Hits volume 1 (Shania Twain)
    Cassette - Love Songs (Michael Jackson)

    Bin B
    DVD - The Later Years (Eminem)

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,420
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Java IndexOutOfBound

    What is printed out by the println statements you are using for debugging? Call println every time something is added to Bin A and Bin B to see what is placed in each bin.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Member
    Join Date
    Dec 2012
    Posts
    127
    My Mood
    Angelic
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Java IndexOutOfBound

    "add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-3: 1000]
    add() mC= [SKU 1234-3: 1000]
    add() mC= [SKU 1234-3: 1000]
    "
    String s = "";
     
            for (Bin b : warehouse) 
            {   s += "Bin "+b.getName()+"\n";
                for(int i = 0  ; i <  b.getContents().size();i++)
                {
                    s += catalog.get(i).toString()+","+ b.getContents().get(i)+"\n";
                }
                s+= "\n";
                    }
            return s;

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,420
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Java IndexOutOfBound

    add() mC= [SKU 1234-3: 1000]
    add() mC= [SKU 1234-3: 1000]
    add() mC= [SKU 1234-3: 1000]
    That looks like the same thing is being added to the llist three times. Is that correct? Which Bin is it being added to?

    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    This print out shows the list as always having 3 items in it? How can that be? I'd expect to see the list with one item and then with two items when a second item is added and then with three items when the next item is added.
    The printout does not make sense.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Member
    Join Date
    Dec 2012
    Posts
    127
    My Mood
    Angelic
    Thanks
    19
    Thanked 0 Times in 0 Posts

    Default Re: Java IndexOutOfBound

    Sorry. I mess up with putting the println you gave me earlier in the wrong method. Here is the correct one.
    "add() mC= []
    add() mC= [SKU 1234-0: 500]
    add() mC= [SKU 1234-0: 500, SKU 1234-1: 25]
    add() mC= []
    getContents() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    getContents() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    getContents() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    getContents() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    getContents() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    getContents() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    getContents() mC= [SKU 1234-0: 500, SKU 1234-1: 25, SKU 1234-2: 7720]
    getContents() mC= [SKU 1234-3: 1000]
    getContents() mC= [SKU 1234-3: 1000]
    getContents() mC= [SKU 1234-3: 1000]
    "

         public ArrayList<BinItem> getContents()
        {System.out.println("getContents() mC= "+ myContents);
            return myContents;
     
        }
     
            public void add(BinItem b)
        {System.out.println("add() mC= "+ myContents);
              myContents.add(b);
        }

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,420
    Thanks
    49
    Thanked 2,215 Times in 2,188 Posts

    Default Re: Java IndexOutOfBound

    The printout should show what is in the list AFTER the item is added.
    The printouts show that three items were added to one bin and one item was added to the other.
    Then the getContents() method was called 7 times for one bin and 3 times for the other bin.
    Why are there so many calls to the getContents() method? The call to getContents() should be moved out of the inner loop so it is only called one time in the outer loop.

    The printouts show there are 3 items in one bin and one item in the other bin.

    So the data is there.

    Now you need to look at why the code doesn't get the correct number of items from each bin.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. IndexOutOfBound
    By Kumarrrr in forum Collections and Generics
    Replies: 3
    Last Post: February 26th, 2010, 05:25 AM