5

I am taking the size of an array in a variable in a loop. Each time I have to assign the size of the array equal to that variable and then take integers equal to that size. For example:

for(i = 0; i < N; i++)
{
    variable = sc.nextInt();
    int []array = new int[variable];
    for(j = 0; j < variable; j++)
    {
        array[j] = sc.nextInt();
    }
}

Please provide me the most efficient method as I am new to java :)

16
  • why this first loop for(i=0;i<N;i++) ? Commented May 26, 2017 at 16:31
  • Would an ArrayList suffice? Commented May 26, 2017 at 16:31
  • 6
    "Please provide me the most efficient method as I am new to java :)" StackOverflow is not a website where you post a problem and get code in return. Please explain what is wrong with your current implementation and we might be able to help. Commented May 26, 2017 at 16:34
  • 2
    what's wrong with using the code you posted? Commented May 26, 2017 at 16:34
  • @YCF_L as i mentioned in question i want N variables and each time I want to make an array of size of that variable i.e., size of array equal to the variable and such N arrays. Commented May 26, 2017 at 16:34

3 Answers 3

1

Maybe you need something like this :

List<int[]> list = new ArrayList<>();//create a list or arrays
for (int i = 0; i < n; i++) {

    int variable = sc.nextInt();
    int[] array = new int[variable];
    for (int j = 0; j < variable; j++) {
        array[j] = sc.nextInt();
    }

    list.add(array);//add your array to your list
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a list of arrays and initialize them on outer loop and add values to arrays using position i and j.

// initialize list with n, though you can also use 2D array as well
List<int[]> array = new ArrayList<>(n);

for (int i = 0; i < n; i++) { 
    variable = sc.nextInt();

    // create an array and add it to list
    array.add(new int[variable]);

    for (int j = 0; j < variable; j++) {
        // fetch the array and add values using index j
        array.get(i)[j] = sc.nextInt();
    }
}

Comments

-1
for(i=0;i<N;i++)
{
    variable = sc.nextInt();
    ArrayList array = new ArrayList(variable)
    for(j=0;j<variable;j++)
    {
        int input = sc.nextInt()
        array.add(input);
    }
}

If an ArrayList works, this is how I'd do it.

1 Comment

OP asks for array initialization, therefore this is no answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.