user10290452
user10290452

Reputation:

How to input array as a parameter in method?

I'm supposed to print a table of array values against their key values. However I receive '.class' expected. But I don't know what is wrong with the code. Please help!

class createTable {
    public static void main (String args []){
        int array[] = {2,13,15,67,87,34,66,23,11,93};
        printTable (array[]);
    }

    static void printTable (int[] array){
        System.out.println ("Key\tValue");
        for (int key = 0; key < array.length; key++){
            System.out.println (key + "\t" + array [key]);
        }
    }
}

Upvotes: 0

Views: 3362

Answers (3)

hipposay
hipposay

Reputation: 62

when you write int array[] = {...}; is the same as writing int[] array = {...}

You are telling the JVM that you are creating an object of type int[] (array of int) with reference name array. When you want to pass the array as a method parameter you have to write the reference name between brackets.

class createTable {
    public static void main (String args []){
        int array[] = {2,13,15,67,87,34,66,23,11,93};
        printTable (array);
    }

    static void printTable (int[] array){
        System.out.println ("Key\tValue");
        for (int key = 0; key < array.length; key++){
            System.out.println (key + "\t" + array [key]);
        }
    }
}

Upvotes: 1

drowny
drowny

Reputation: 2147

Remove brackets when sending to methods as a parameter. Only with param name also.

So code will be like this:

class createTable {
    public static void main (String args []){
        int array[] = {2,13,15,67,87,34,66,23,11,93};
        printTable (array);
    }

    static void printTable (int[] array){
        System.out.println ("Key\tValue");
        for (int key = 0; key < array.length; key++){
            System.out.println (key + "\t" + array [key]);
        }
    }
}

Upvotes: 2

Jakub Keller
Jakub Keller

Reputation: 497

Remove the [] from your argument when calling printTable.

printTable (array);

Upvotes: 5

Related Questions