Use an array in multiple methods

TommyDordo :

I am creating a program with 2 methods.

In the first method I create an array, and in the second method I have to display that array like a table.

So my question is, how do I create an array in the first method and pass it to the second method for displaying?

public class test {

    public static void main(String[] args) {
        first();
        second();
    }
    public static void first () {
        int N= (int)(Math.random()*5)+1;
        int M= (int)(Math.random()*5)+1;
        int v [][] = new int [N][M];
        for(int i=0; i < v.length; i++) {
            for(int j=0; j < v[0].length; j++) {
                v [i][j]= (int)(Math.random()*5);
            }
        }
    }
    public static void second () {
        for(int i=0; i < v.length; i++) { 
            for(int j=0; j < v[0].length; j++)
                System.out.print(v [i][j] + " ");
            System.out.println("");
        }
    }
}

how can I pass the array "v" in the second method?

dan1st :

If the first method calls the second method, just pass it as parameter:

public void doStuff(){
    int[] arr;//initialize
    useArray(arr);
}
public void useArray(int[] arr){
     //use it
}

If both methods are ececuted one after another, return it, save it to a variable and pass it:

public void outerMethod(){
    int[] arr=createArray();
    useArray(arr);
}
public int[] createArray(){
    int[] arr;
    //initialize it
    return arr;
}
public void useArray(int[] arr){
    //use arr
}

In your case, this would be:

public class test {

    public static void main(String[] args) {
        int[] v=first();
        second(v);
    }
    public static int[][] first () {
        int N= (int)(Math.random()*5)+1;
        int M= (int)(Math.random()*5)+1;
        int v [][] = new int [N][M];
        for(int i=0; i < v.length; i++) {
            for(int j=0; j < v[0].length; j++) {
                v [i][j]= (int)(Math.random()*5);
            }
        }
        return v;
    }
    public static void second (int[][] v) {
        for(int i=0; i < v.length; i++) { 
            for(int j=0; j < v[0].length; j++)
                System.out.print(v [i][j] + " ");
            System.out.println("");
        }
    }
}

[Notes]

This does not only work with integer arrays but also any other array.

In fact, this works with any type.

By convention, class names should be written PascalCase and variable (and method) names should be written camelCase.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=348960&siteId=1