1

**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
1
  • 2
    The same way you create any other array. Commented Dec 11, 2013 at 15:09

4 Answers 4

4

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()]);
Sign up to request clarification or add additional context in comments.

3 Comments

Are you creating an Integer array named myNumbers at the end??shoudnt it be int [] myNumbers ?cz when we want to declare an integer array thats the way we do it right?
Type mismatch: cannot convert from Integer[] to int[]
Rather do: ``` int [] myNumbers = new int[numbers.size()]; for (int i=0; i < numbers.size(); i++) myNumbers[i] = numbers[i]; ``` but hey, I'm more of a C# guy, so just a suggestion.
3
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
                                        }

                      }

Comments

1
int[] numbers = new int[SIZE_OF_ARRAY_HERE];

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

2 Comments

Yeah i want to know how to use ArrayList ? Can you explain the way i can use it by an example?
I would start by reading java.util.ArrayList
1

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.

Comments

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.