-1

I'm new to using array lists and would like to ask why I am getting an index out of bounds exception when I explicitly state that my students array list must be larger than zero before trying to access it in my if statement on line 23.

I am not sure what I am doing wrong and could really use some help. Thank you.

My code:

import java.util.Scanner;
import java.util.ArrayList;
public class Test {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    ArrayList<Student> students = new ArrayList<Student>();
    String name = "";
    int age = 0;
    int GPA = 0;
    boolean running = true;

    while(running) {
        name = input.next();
        if(name.equals("next") && students.size() > 0) {
            students.remove(0);
            continue;
        } else if(name.equals("end")) {
            running = false;
        }
        age = input.nextInt();
        GPA = input.nextInt();
        Student newStudent = new Student(name, age, GPA);
        if(students.size() > 0 && age < students.get(students.size() - 1).getAge() || GPA < students.get(students.size() - 1).getGPA()) {
            String tempName = students.get(students.size() - 1).getName();
            int tempAge = students.get(students.size() - 1).getAge();
            int tempGPA = students.get(students.size() - 1).getGPA();
            Student tempStudent = new Student(tempName, tempAge, tempGPA);
            students.remove(students.size() - 1);
            students.add(newStudent);
            students.add(tempStudent);
        } else {
            students.add(newStudent);
        }
    }

    if(students.size() == 0) {
        System.out.println("empty");
    } else {
        for(int i = 0; i < students.size(); i++) {
            System.out.println(students.get(i).getName());
        }
    }
}

}

  • Where did you give the size for your arraylist? you should first provide a value to be checked if it's larger than zero – Vishwa Jan 25 '18 at 06:23

2 Answers2

3

The array is zero based (the items are indexed 0,1,2,3...n-1 where n is the number of items), so students.get(students.size()) will always fail with an out-of-bounds. It should be students.get(students.size()-1).

Kristof
  • 104
  • 4
  • That's what I had before. I just changed it back and now the array index is -1? –  Jan 25 '18 at 06:25
  • That's confusing to me though because I have it check if there's an element in the array before it tries to access it. –  Jan 25 '18 at 06:26
  • If there's 1 item, then 1 -1 == 0, which is the first time of the arraylist. – Kristof Jan 25 '18 at 08:29
0

you als should not use while(true) if possible, because its not so elegant. Rather state the condition to continue in brackets.

Are "while(true)" loops so bad?

floboe
  • 25
  • 2
  • 8