Mr_Higgins
Mr_Higgins

Reputation: 27

display an array from another method in java

public class Lab6 {

    public static void main(String[] args) {
        int List1[] = new int[10];
        List1[0] = 1;
        List1[1] = 3;
        List1[2] = 4;
        List1[3] = 5;
        List1[4] = 2;
        List1[5] = 6;
        List1[6] = 8;
        List1[7] = 9;
        List1[8] = 2;
        List1[9] = 7;
        toDisplay(List1);

    }
    public static void toDisplay (List1){
        int i;
        for(i=0; i>10; i++){
            System.out.print(List[i] + " ");
        }
    }
}

It will not carry over and recognize my List1 array. How do I display the List1 array in another method without making it a global?

Upvotes: 0

Views: 68

Answers (2)

Andrew
Andrew

Reputation: 49656

Change List1 to int[] List1 in the formal parameters of the toDisplay method. By JCC, also you should rename the next names:

List1 -> list1
toDisplay -> display

What about this?

public static void display(int[] list){
    Arrays.stream(list).forEach(System.out::println);
}

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201527

To pass an int[] to toDisplay (and the loop condition should be < not >). Something like

public static void toDisplay (int[] List1){
    int i;
    for (i=0; i < List1.length; i++) {
        System.out.print(List1[i] + " ");
    }
}

Upvotes: 4

Related Questions