【问题标题】:How do I invoke a method with array parameter in java? [closed]如何在java中调用带有数组参数的方法? [关闭]
【发布时间】:2013-12-17 08:02:43
【问题描述】:

我有一个任务,我必须在 Java 中对数组执行操作,我必须为每个操作创建单独的函数,我将编写这些函数,但我不知道如何调用具有数组参数的方法。我通常用 c++ 编程,但这个作业是用 java 编写的。如果你们中的任何人可以帮助我,我将非常感激。 :)

public class HelloJava {
    static void inpoot() {
        Scanner input = new Scanner(System.in);
        int[] numbers = new int[10];

        System.out.println("Please enter 10 numbers ");
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = input.nextInt();
        }
    }

    static void outpoot(int[] numbers) {
        for(int i = 0; i < numbers.length; i++) { 
                System.out.println(numbers[i]); 
        }
    }

    public static void main(String[] args) {
        inpoot();
        outpoot(numbers); //can not find the symbol
    }
}

【问题讨论】:

  • 像这样:outpoot(numbers)numbers 数组应该来自哪里?
  • 来自 inpoot() 函数中的用户。
  • 如果你用 C++ 编程,你应该已经知道调用以数组为参数的方法是完全一样的。
  • 所以在 C++ 中,你将一个在其他地方声明的变量传递给函数,我明白了......
  • 我同意,我完全不正确,这就是我在这里提出问题的原因。你们不必刻薄。我只是在寻求帮助。

标签: java arrays methods invocation


【解决方案1】:

您的inpoot 方法必须返回int[] 数组,然后将其作为参数传递给outpoot

public class HelloJava {    
    static int[] inpoot() { // this method has to return int[]
        Scanner input = new Scanner(System.in);
        int[] numbers = new int[10];

        System.out.println("Please enter 10 numbers ");
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = input.nextInt();
        }
        return numbers; // return array here
    }

    static void outpoot(int[] numbers) {
        for(int i = 0; i < numbers.length; i++) { 
            System.out.println(numbers[i]); 
        }
    }

     public static void main(String[] args) {
        int[] numbers = inpoot(); // get the returned array
        outpoot(numbers); // and pass it to outpoot
    }
}

【讨论】:

    【解决方案2】:

    当你调用 outpoot 时,它应该是 输出(数字);

    【讨论】:

    • 不行,我试过了。出现“找不到符号”错误。
    • 这是因为 numbers 是 inpoot 方法中声明的局部变量。超出范围我是主要方法
    • 这就是我要问的,我如何在那里传递数字数组。我的意思是,我该怎么做才能让它从 inpoot 中获取数组并将其传递给 main 函数的 outpoot 调用。
    • 您可以让 inpoot 方法返回数组而不是 void。然后在 main 方法中将其作为参数传入。
    • 哦,谢谢,这确实有效。 :)
    猜你喜欢
    • 2013-07-17
    • 2016-07-05
    • 2014-06-30
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多