BreadCat
BreadCat

Reputation: 23

What exactly is wrong with my ArrayList?

My program compiles, but when I run it, it gives me an IndexOutOfBoundsException. I am wondering what is wrong with it as I am unable to see it. My program is supposed to take input by the user and add it to the ArrayList. I am sorry if my mistake is obvious to you, but I am relatively new at using ArrayLists. Thanks!

ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
int counter = 0;
int i = 0;
Scanner in = new Scanner(System.in);
int input = in.nextInt();

while(i < 5)
{
    input = in.nextInt();
    if(input != 0){
        arr.get(i).set(counter++, input);
    }
    else{
        arr.get(i).set(counter++, input);
        i++;
        counter = 0;
    }
}

System.out.println(arr);

Upvotes: 1

Views: 75

Answers (2)

sandeep verma
sandeep verma

Reputation: 149

You are creating a list of list and both are empty. Also you are using "set" method which is actually used to replace the object in a list on specific location.

So it looks like you wanted to take input from user and if the value is 0 you just wanted to ignore it. Below is the update example for you.

    ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
    int i = 0;
    Scanner in = new Scanner(System.in);
    int input = 0;
    while(i < 5){
        input = in.nextInt();
        if(input != 0){
            arr.add(new ArrayList<Integer>());
            arr.get(i).add(input);
            i++;
        }

    }

    System.out.println(arr);

If you just want to create a list of integers then you don't have need to create a list of list. You can achieve by creating a list of integer only.

 ArrayList<Integer>  arr = new ArrayList< Integer >();
    int i = 0;
    Scanner in = new Scanner(System.in);
    int input = 0;
    while(i < 5){
        input = in.nextInt();
        if(input != 0){
            arr.add(input);
            i++;
        }

    }

    System.out.println(arr);

Upvotes: 0

rgettman
rgettman

Reputation: 178333

When you create your ArrayList of ArrayLists, initially, there are no ArrayLists contained in arr. So any call to get will fail with a IndexOutOfBoundsException.

First, add the initial inner ArrayList to arr.

Then, in the while loop, get the current inner ArrayList as you're doing, but just call add to append a number to the end of the list. Otherwise, you'll get a IndexOutOfBoundsException on your inner ArrayList. Again, the ArrayList you've created is initially empty.

When the user enters 0, then add another ArrayList when you're incrementing i (unless i is already at the last desired value), to prepare for the user adding numbers to the next list.

Upvotes: 3

Related Questions