【问题标题】:How to declare array in method [duplicate]如何在方法中声明数组[重复]
【发布时间】:2017-09-02 05:52:50
【问题描述】:

我目前必须编写一个接收两个参数的方法:一个名为 data 的整数数组和一个名为 num 的整数。此方法的目的是计算该数字在数组中出现的次数。我无法弄清楚如何在方法中声明数组。我想知道下面是否有更简单的方法:

方法

public static void countNumbers( int data[], int num ) {
        int count = 0;

        for(int i = 0; i < data.length; i++) {
            if(data[i] == num)
                count++;
        }
        if (count == 0)
            System.out.println("There are no " + num + "'s in the array.");
        if (count == 1)
            System.out.println("There is one " + num + " in the array.");
        if (count > 1)
            System.out.println("There are: " + count + " " + num + "'s in the array.");
}

主类

public static void main(String args[]) {
        int firstArray[] = {1,2,3,4,5};
        Methods.countNumbers(firstArray, 2);
    }

所以我想知道您是否可以直接在 countNumbers(data,num) 中声明该数组,任何帮助将不胜感激!

【问题讨论】:

  • 我不明白你的问题——你在方法参数中声明了数组并且似乎这样做得当。那么这到底是怎么回事?什么让你感到困惑。
  • 我想知道是否有任何方法可以在方法中声明数组,例如:Methods.countNumbers(int firstArray[] = {1,2,3} , 2);
  • 如果你没有在其他任何地方引用它(你在其他任何地方都不需要它),只需执行 Methods.countNumbers({1, 2, 3}, 2)
  • @MCMastery 我认为这不会编译。

标签: java arrays


【解决方案1】:

这就是你要找的吗?

public static void main(String args[]) {
    Methods.countNumbers(new int[] {1,2,3,4,5}, 2);
}

【讨论】:

  • 这正是我想要的,非常感谢。我还不能接受答案!
  • 哈,很高兴我能帮上忙。不用担心,一旦您获得更多代表,您随时可以回来。 :)
猜你喜欢
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 2021-11-05
  • 2012-10-15
  • 1970-01-01
相关资源
最近更新 更多