-2

I would like to use input an array of arraylist, where the first input is the number of arrays of arraylist and the next line represents the input for each array. Please let me know where am going wrong. Please find below the code for the same:

public static void main(String[] args) {     
    Scanner input = new Scanner(System.in);
    int a = input.nextInt();
    ArrayList[] al = new ArrayList[a];
    for( int i =0; i<a; i++){            
        while(input.hasNextLine())
            {
              al[i].add(input.nextInt());
            }
    }
    System.out.print("result is"+al[0]);        
}
  • 1
    This isn't how you use an ArrayList. – intboolstring Jun 16 '16 at 15:30
  • It does compile. He/She's just using raw types. http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – JB Nizet Jun 16 '16 at 15:32
  • You've created an empty array of `ArrayList`, but you aren't initializing the `ArrayList` before trying to add to it. Call `al[i] = new ArrayList()` before you begin the while loop to add to it to solve that problem. But also, intboolstring is right - this is not a good use case for `ArrayList`. – Krease Jun 16 '16 at 15:42

1 Answers1

1

Try this out.

   for( int i =0; i<a; i++){       
        ArrayList<int> temp = new ArrayList<int>();
        while(input.hasNextLine())
            {
              temp.add(input.nextInt());
            }
         al[i] = temp;
    }
Andrew
  • 208
  • 1
  • 12
  • Hi Andrew, this is fine but it takes all the input on different lines and assigns it to the first array. How can i have it in the next array – Sai Mithun Nakka Jun 16 '16 at 19:47
  • `while input.hasNextLine(){ ArrayList temp = new ArrayList(); temp.add(input.nextInt()); al[i] = temp; }` Formatting in comments isn't great, but hopefully this helps! – Andrew Jun 17 '16 at 14:05