Razor1692
Razor1692

Reputation: 153

How create an array in run time in java?

**I want to know how to create an array in run time in java? For an instance say that i want to check the numbers which divides 498 ,and i want to put them into an array ?

for(i=1;i<=498/2;i++){
   int z=498%i;
   if(z==o)// put the i into the array if not continue

Upvotes: 1

Views: 12008

Answers (4)

Jagdish Singh
Jagdish Singh

Reputation: 31

import java.io.*;
import java.util.*;
public class Solution {

public static void main(String[] args) { 

   Scanner scan= new Scanner(System.in);
   int size=scan.nextInt();         //Enter size of array
   int[] array = new int[size];     //create array at runtime
                                        }

                      }

Upvotes: 3

dev2d
dev2d

Reputation: 4262

you can create an ArrayList while iterating for loop and later you can convert it to Array like below if you need an array at the end of process

integer [] myNumbers = list.toArray(new Integer[list.size()]);

this will help you not worrying about re sizing of Array at runtime

so finally your code should look like following

List<Integer> numbers = new ArrayList<Integer>();
for(i=1;i<=498/2;i++){
   int z=498%i;
   if(z==o){
     numbers.add(i);
   }
}

int [] myNumbers = numbers.toArray(new Integer[numbers.size()]);

Upvotes: 4

Melquiades
Melquiades

Reputation: 8598

I understand that by "at runtime", you mean that you don't know the size of an array at the beginning, and want the array to grow if needed (correct me if I'm wrong). You can use ArrayList for this:

  1. Declare your list first:

    List<Integer> myList = new ArrayList<Integer>();
    
  2. Use it in your loop:

    for (int i=1; i<=498/2; i++) {
        int z = 498 % i;
    
        if (z == 0) {
            //add i to the list
            myList.add(i);
        }
    }
    
  3. You can then print the list with:

    System.out.println(myList.toString());
    

Please read about ArrayLists here, or just google it, there's plenty tutorials on ArrayLists.

Upvotes: 1

Tim B
Tim B

Reputation: 41188

int[] numbers = new int[SIZE_OF_ARRAY_HERE];

Or if you want to be able to resize it use an ArrayList instead.

Upvotes: 1

Related Questions