Results 1 to 8 of 8
  1. #1
    Arius is offline Member
    Join Date
    Jan 2010
    Posts
    5
    Rep Power
    0

    Default ArrayList IndexOutOfBounds... error

    Hey guys, I just joined the forums and hope to learn a lot about programming here.

    So, I have an assignment to make a code calculating the mode of a text file with 999 integers. I know there are probably more efficient ways to solve this problem, but I want to stick with my code and just fix it. I'm trying to make one ArrayList with the occurrences(frequencies) of each of the 999 integers in the text file, and get the mode that way.

    I keep on receiving this error
    "IndexOutOfBoundsException: Index: 1, Size: 1)"
    when I try to run my code, and the highlighted error is on my "numbers.remove..." and on "backUp.remove..." in my public intCalcFinalMode() method. I know what the error means, but I've tried everything and I cannot find a way to fix it. Can someone please point out my error? Thanks.

    Java Code:
    import java.util.ArrayList;
    import java.lang.Math;
    
    
    public class Statistics
    {
        private ArrayList<Integer> numbers = new ArrayList<Integer>();
        private ArrayList<Integer> occurrences =new ArrayList<Integer>();
        private ArrayList<Integer> finalMode = new ArrayList<Integer>();
        private ArrayList<Integer> backUp = new ArrayList<Integer>();
        
        public Statistics()
        {
        } //end default constructor
        
        public Statistics(ArrayList<Integer> inputNumbers)
        {
            numbers = inputNumbers;
        } //end non-default constructor
        public void calcOccurrences()
        {
            
            for(int currentNumber : numbers)
            {
                int counter = 0;
                int numberOfOccurrences = 0;
                while (counter < numbers.size())
                {
                    if (currentNumber == numbers.get(counter))
                    {
                        numberOfOccurrences++;
                        counter++;   
                    } else {
                        counter++;
                    } //end if
                    
                    
                
                
                } //end while statement
                occurrences.add(numberOfOccurrences); 
                backUp.add(numberOfOccurrences);
                
             } //end extended for loop
        } //end method
       
       public int calcFinalMode()
       {
    
          
           for(int currentOccurrence : occurrences)
           {
                int facto=0;
                int counter = 0;
               while (counter < occurrences.size())
               {
                    if (currentOccurrence >= occurrences.get(counter))
                    {
                        counter++;
                       
                     
                    } else {
                        
                        [B]numbers.remove(occurrences.indexOf(currentOccurrence));
                        backUp.remove(occurrences.indexOf(currentOccurrence));[/B]
                    } //end LONG if
                    
               } // end while loop
             facto = numbers.get(backUp.indexOf(currentOccurrence));   
             finalMode.add(facto);
            
            } //end extended for loop
    
            return finalMode.get(0);
    
        } //end method
        
        public int calcOtherMode()
        {
            int otherMode = 0;
            finalMode.remove(0);
            if (!finalMode.isEmpty())
            {
                otherMode = finalMode.get(0);
            } //end if statment
            return otherMode;
        } //end method
            
     
    } //end class


    DRIVER --------------------------------
    Java Code:
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class StatisticsDriver
    {
        public static void main(String args[])
        {
            ArrayList<Integer> numbers = new ArrayList<Integer>();
              
            Scanner in;
            try {
            in = new Scanner(new File("numbers.txt"));
            while(in.hasNextInt())
            {
               numbers.add(in.nextInt());
            } //end while loop
           
            } catch(IOException i) {
               System.out.println("Error: " + i.getMessage());
            } //end file-read
        
            Statistics myStatistics = new Statistics(numbers); 
            myStatistics.calcOccurrences();
            System.out.println("Mode: " + myStatistics.calcFinalMode()  +  ", " + myStatistics.calcOtherMode());
            
         }// end main
    
    } //end class
    Last edited by Fubarable; 01-17-2010 at 07:25 PM. Reason: code tags added

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    When you remove something from an array list, everything in the arraylist that was after it slides over one index. Think of removing a middle dish from a pile of dishes -- all the dishes above the removed one are located one index less than before. Now if you remove an item from an array list using a for loop that is counting forward, this is a recipe for disaster, since after one removal, all items above are not going to be located at the index you think they're at. One solution is to loop using the list's iterator, another is to use a for loop that counts backwards.

    Oh, and welcome to the forum! Please if you can read my signature about using code tags when posting code here.

    Best of luck!

  3. #3
    Arius is offline Member
    Join Date
    Jan 2010
    Posts
    5
    Rep Power
    0

    Default

    Oh i see, so I would be working against the current of the for loop. In order to loop counting backwards, would I have to change the counter instantiation to counter = 998 (because there are 999 numbers in the list),and decrement the counter (counter--)? Or is there a completely different form to it...

    I'm sorry about the code, I found the button. And thanks a bundle for replying!

    Java Code:
    public int calcFinalMode()
       {
    
          
           for(int currentOccurrence : occurrences)
           {
                int facto=0;
                i[B]nt counter = 998;[/B]
               while (counter < occurrences.size() [B]&& counter >= 0)[/B]
               {
                    if (currentOccurrence >= occurrences.get(counter))
                    {
                        [B]counter--;[/B]
                       
                     
                    } else {
                        
                        numbers.remove(occurrences.indexOf(currentOccurrence));
                        backUp.remove(occurrences.indexOf(currentOccurrence));
                    } //end LONG if
                    
               } // end while loop
             facto = numbers.get(backUp.indexOf(currentOccurrence));   
             //finalMode.add(facto);
    Last edited by Arius; 01-17-2010 at 08:15 PM. Reason: it would be 998, not 999, sorry, because of counting from 0

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Myself, I would solve this using a HashMap<Integer, Integer>, the first Integer being the number found in the list, the second Integer being the number of times that it was found. So when a number is read in, the map is checked to see if this number has already been entered (calling get(thisNumber) on the map will return a non-null Integer -- the current count for this number). If null, you create a new entry for the map with the key being this number and the value being 1. If not null, then take the return value, increment it by one and create a new entry for the map again with the key being the number read and the value being the updated value:

    Java Code:
        Map<Integer, Integer> occurMap = new HashMap<Integer, Integer>();
        Scanner scan = new Scanner(file);
        while (scan.hasNextInt()) {
          int nextInt = scan.nextInt();
          if (occurMap.get(nextInt) == null) {
            occurMap.put(nextInt, 1);
          } else {
            occurMap.put(nextInt, occurMap.get(nextInt) + 1);
          }
        }

  5. #5
    Arius is offline Member
    Join Date
    Jan 2010
    Posts
    5
    Rep Power
    0

    Default

    Yeah many people have told me hash map is the efficient way to solve it, and you are certainly correct, but the problem is, for my assignment in class, my teacher does not allow it. He wants us to focus on raw Array Lists.

  6. #6
    Arius is offline Member
    Join Date
    Jan 2010
    Posts
    5
    Rep Power
    0

    Default

    I revised it to include a backwards for loop, but it's still giving me an IndexOutOfBoundsException: Index: 998, Size: 998.
    Java Code:
      public int calcFinalMode()
       {
    
          
           for(int i = (occurrences.size() - 1); i < occurrences.size() && i >= 0; i--)
           {
                int facto=0;
                int counter = (occurrences.size()-1);
               while (counter < occurrences.size())
               {
                    if (occurrences.get(i) >= occurrences.get(counter) && counter >=0)
                    {
                        counter--;
                       
    
                     
                    } else {
                        numbers.remove(i);
                        backUp.remove(i);
                        
                    } //end LONG if
                    
               } // end while loop   
             facto = numbers.get(i);
             finalMode.add(facto);
            
            } //end extended for loop
            return finalMode.get(0);
        } //end method

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I'm not sure what you're doing with this code above.

    If you can't use a HashMap, why not just use an array of ints and use the number read in as the index number to the array, incrementing the int held at the index's position?

  8. #8
    Arius is offline Member
    Join Date
    Jan 2010
    Posts
    5
    Rep Power
    0

    Default

    Sorry I know it is unclear. An array list of ints with the number read in as the index number to the array... I'm not sure If I understand your method. Can you provide a brief example? Thank you for your troubles.

Similar Threads

  1. Replies: 1
    Last Post: 12-05-2009, 07:28 AM
  2. Replies: 1
    Last Post: 10-26-2009, 04:38 PM
  3. Replies: 3
    Last Post: 01-23-2009, 08:53 AM
  4. Confusing IndexOutOfBounds Error?
    By tibbyuk in forum New To Java
    Replies: 2
    Last Post: 08-08-2008, 11:42 PM
  5. Replies: 2
    Last Post: 04-21-2008, 11:43 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •