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

Thread: Error message java.lang.ArrayIndexOutOfBoundsException: 0

  1. #1
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Error message java.lang.ArrayIndexOutOfBoundsException: 0

    Hey guys, this is my first time on here so I don't know if my code is going to come out messy, so if it does I'm sorry. I'm new to java programming and I'm working on an assignment where I was given the main method and one constructor class, and I had to create the other constructor class myself. However when I run the program, the main method complains at the line:

    int size = Integer.parseInt(args[0]);

    And says "java.lang.ArrayOutOfBoundsException: 0" I'm not sure what this means, but here is my constructor class StudentCollection along with the main method if that helps. Could anyone tell me what I am doing wrong?

    public class StudentCollection
    {
        private double averageGPA;
        private int count;
        private Student[] collection;
     
        public StudentCollection(int initialSize){
            collection=new Student[initialSize];
            count=0;
        }
     
        public void addToCollection(Student s) {
            if(count==collection.length) {
                increaseSize();
            }
            collection[count]=s;
            count++;
        }
     
        private void increaseSize() {
            Student[] collection2=new Student[collection.length*2+1];
            System.arraycopy(collection, 0, collection2, 0, count);
            collection=collection2;
        }
     
        public double getAverageCreditsCompleted() {
            double sum=0;
            if(count>0) {
                for(int i=0; i<count; i++) {
                    sum=sum+collection[i].getCreditsCompleted();
                }
                return sum/count;
            }
                else return 0;
        }
     
        public double getAverageGPA() {
            double sum=0;
            if(count>0) {
            for(int i=0; i<count; i++) {
                sum=sum+collection[i].getGPA();
            }
            return sum/count;
          }
            else return 0;
        }
     
        public int getCount() {
            return count;
        }
     
        public boolean removeFromCollection(java.lang.String name) {
            for(int i=0; i<count; i++) {
                if(collection[i].getName().toUpperCase().equals(name.toUpperCase())) {
                collection[i]=collection[count-1];
                count--;
                return true;
            }
               else return false;
           }
           return false;
        }
     
        public String toString() {
            String stuString="";
                for(int i=0; i<count; i++) {
                    stuString=stuString+collection[i];
                }
                return stuString;
        }
     }

    And here is the main method:
    public class Lab8  {
        public static void main (String[] args)  {
            // Scanner to read input from the keyboard
            Scanner keyboard = new Scanner(System.in);
            int size = Integer.parseInt(args[0]);  // use "2" when you run the program
     
            StudentCollection collection = new StudentCollection(size);
            Student s;  // s is a Null reference at this point
            String name, major;
            int credits;
            double gpa;
            int choice;
            DecimalFormat df = new DecimalFormat("0.00");
     
            String line;
     
            do {
                System.out.println();
                System.out.println("\t1. Add a new Student to the collection");
                System.out.println("\t2. Remove a Student from the collection");
                System.out.println("\t3. Display the students in the collection");
                System.out.println("\t4. Display statistics");
                System.out.println("\t5. Quit the program");
     
                System.out.print("\nYour selection: ");
                choice = Integer.parseInt(keyboard.nextLine() );
     
                switch(choice) {
                   case 1: 
                       System.out.print("Enter the student's full name: ");
                       name = keyboard.nextLine();
     
                       System.out.print("Enter the students gpa: ");
                       line = keyboard.nextLine();
                       gpa = Double.parseDouble(line);
     
                       System.out.print("Enter the student's major: ");
                       major = keyboard.nextLine();
     
                       System.out.print("Enter the number of credits completed by the student: ");
                       line = keyboard.nextLine();
                       credits = Integer.parseInt(line);
     
                       s = new Student(name, gpa, major, credits);
                       collection.addToCollection(s);
                       break;
     
                   case 2:
                       System.out.print("Enter the name of the student that is to be removed: ");
                       name = keyboard.nextLine();
                       boolean result = collection.removeFromCollection(name);
                       if (result) 
                          System.out.println("Student with name " + name  + " is successfully removed");
                       else
                           System.out.println("There is no Student whose name is " + name);
                       break;
     
                   case 3:
                       System.out.println(collection);
                       break;
     
                   case 4:
                       System.out.println("There are " + collection.getCount() + " students in the collection");
                       System.out.println("Average GPA of the students in the collection: " +
                                   df.format(collection.getAverageGPA() ));
                       System.out.println("Average number of credits completed by the students " +
                                   "in the collection: " + collection.getAverageCreditsCompleted() );
                       System.out.println();
                       break;
     
                   case 5:
                       System.out.println("Thank you for using my program.  Good bye!");
                       System.exit(0);   // quit the program
     
                   default:
                       System.out.println("Illegal Choice.  Try again");
                }   // end of switch
            } while (choice != 5);   
        }  // main method
    }

    Thank you, I appreciate the help.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Error message java.lang.ArrayIndexOutOfBoundsException: 0

    java.lang.ArrayOutOfBoundsException: 0
    The error message says that the array is empty (it does NOT have an element at index 0).
    The code needs to test if the array has one or more elements BEFORE trying to access the first element.
    Use the array field: .length to test the length: if(theArray.length > 0) ...
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Error message java.lang.ArrayIndexOutOfBoundsException: 0

    Quote Originally Posted by Norm View Post
    Use the array field: .length to test the length: if(theArray.length > 0) ...
    How will this stop the error message from happening? And where do I put this if statement?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Error message java.lang.ArrayIndexOutOfBoundsException: 0

    where do I put this if statement?
    Test the array's length BEFORE trying to index into the array.

    How will this stop the error message from happening
    If the array is not long enough, do NOT try to index into it.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Error message java.lang.ArrayIndexOutOfBoundsException: 0

    Isn't it supposed to be empty at index 0? That's where I'm supposed to put my first student object. If I don't index into it, won't that just stop the execution of the program since the if statement won't be met? I'm sorry, I'm really new to this, I have trouble understanding most things with arrays.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Error message java.lang.ArrayIndexOutOfBoundsException: 0

    The indexes for arrays start at 0 and go to the array length-1.
    The first element in an array is at index 0.

    where I'm supposed to put my first student object.
    You never posted the full text of the error message that shows what line the error happens on.
    Look at the error message, get the source code line number and find the source line where the error happens.
    What array is being indexed on that line? I don't know what that line has to do with student objects.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Mar 2013
    Posts
    58
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Error message java.lang.ArrayIndexOutOfBoundsException: 0

    That is all the compiler tells me for the error sir, and it highlights the line
    int size = Integer.parseInt(args[0]);

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Error message java.lang.ArrayIndexOutOfBoundsException: 0

    The code needs to test if the length of the args array is > 0. If it is NOT, the code should NOT try to access index 0.
    A couple of solutions if the length < 1
    Print out an error message to the user and exit the program.
    Assign a default value to the size variable.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 1
    Last Post: February 27th, 2013, 06:48 AM
  2. [SOLVED] Error Message: Exception in thread "main" java.lang.NullPointerException etc.
    By coffecupcake in forum What's Wrong With My Code?
    Replies: 5
    Last Post: November 15th, 2011, 09:34 AM
  3. java.lang.numberformatexception error
    By natalie in forum What's Wrong With My Code?
    Replies: 3
    Last Post: February 19th, 2010, 04:16 AM
  4. an error message while runnung java
    By sravan_kumar343 in forum Java Theory & Questions
    Replies: 1
    Last Post: January 25th, 2010, 10:19 AM
  5. Replies: 2
    Last Post: November 3rd, 2009, 06:28 AM

Tags for this Thread