如何在方法中输入数组作为参数?

我应该根据它们的键值打印一个数组值表。但是我收到'.class' expected. 但我不知道代码有什么问题。请帮忙!


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]);

        }

    }

}


智慧大石
浏览 229回答 3
3回答

白衣非少年

当你写作 int array[] = {...}; 和写作是一样的 int[] array = {...}您告诉 JVM 您正在创建一个类型为int[](int 数组)的对象,其引用名称为 name array。当您想将数组作为方法参数传递时,您必须在括号之间写入引用名称。class createTable {&nbsp; &nbsp; public static void main (String args []){&nbsp; &nbsp; &nbsp; &nbsp; int array[] = {2,13,15,67,87,34,66,23,11,93};&nbsp; &nbsp; &nbsp; &nbsp; printTable (array);&nbsp; &nbsp; }&nbsp; &nbsp; static void printTable (int[] array){&nbsp; &nbsp; &nbsp; &nbsp; System.out.println ("Key\tValue");&nbsp; &nbsp; &nbsp; &nbsp; for (int key = 0; key < array.length; key++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println (key + "\t" + array [key]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

白衣染霜花

[]调用 printTable 时从参数中删除。printTable&nbsp;(array);

蓝山帝景

作为参数发送到方法时删除括号。也只有参数名称。所以代码会是这样的:class createTable {&nbsp; &nbsp; public static void main (String args []){&nbsp; &nbsp; &nbsp; &nbsp; int array[] = {2,13,15,67,87,34,66,23,11,93};&nbsp; &nbsp; &nbsp; &nbsp; printTable (array);&nbsp; &nbsp; }&nbsp; &nbsp; static void printTable (int[] array){&nbsp; &nbsp; &nbsp; &nbsp; System.out.println ("Key\tValue");&nbsp; &nbsp; &nbsp; &nbsp; for (int key = 0; key < array.length; key++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println (key + "\t" + array [key]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java