Serpace
Serpace

Reputation: 83

Creating a 2 dimensional jagged array of undetermined size

For my program, i am making a 2D jagged array of integers and the length of each array inside depends on the input of the user.

Lets say for something like:

int seq [] [] = new int [M] [];
for(int i = 0; i < M; i++){
    seq[i] = new int [N[i]];

The total number of arrays (M) and the N array with length for each array depends on the input by user. Is there a way i can make this so the resultant 2D array can be used by any method inside the class?

Thanks.

Upvotes: 0

Views: 547

Answers (2)

HUSNAIN SARWAR
HUSNAIN SARWAR

Reputation: 95

Yes it is Possible you Take The Size of the Rows and Columns of the Array at run time then Create the Array According to the Size you Provide.

 int m;
 int n;
System.out.println("EnTer size of Row and column");
m = input.nextInt();
n = input.nextInt();
int[] arr = new int[m][n];

Upvotes: 1

Aniket Thakur
Aniket Thakur

Reputation: 69005

You can make it array an instance variable and initialize it in some init method or constructor.

public class Test{
    int[][] array;

    public void initialize() {
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        int n = scanner.nextInt();
        array = new int[m][n];
    }

     public void processArray() {
       if(array != null) {
         //process array
       }
     }
}

Upvotes: 1

Related Questions