繁体   English   中英

方法仅在主要 class 中有效,但在从其他 class 调用时无效

[英]method works only in main class but not when called from its other class

嗨,我写了一个方法来计算一个数字在数组中出现的次数。问题是它在与主程序相同的 class 中写入时有效,但在不同的 class 中写入时无效。

public class Digits {


    public static void main(String[] args) {
        int []b={1,1,1,1,2};

    int c=  Digits.numberCount(b,5);
    System.out.println(c);
    }




      public static int numberCount(int[]numbers,int number){
    int count=0;
    for(int i=0;i<numbers.length;i++){
        if(number==numbers[i])
            count++;
    }
    return count;
          }

}

它在上述实例中有效,但当我尝试使用另一个 class 但在同一个项目中的方法时

public class DigitsA {
    private int[]numbersrange;


    public DigitsA(){
        numbersrange=new int[9];

    }

    public static int numberCount(int[]numbers,int number){
        int count=0;
        for(int i=0;i<numbers.length;i++){
            if(number==numbers[i])
                count++;
        }
        return count;
    }

}

您似乎很困惑...以下是您将如何使用它,以及使用foreach循环使您的代码更清晰:

public class Digits
{

    public static void main(String[] args)
    {
        int[] b = { 1, 1, 1, 1, 2 };
        int c = Digits.numberCount(b, 5);
        System.out.println(c);
    }

    public static int numberCount(int[] numbers, int number)
    {
        int count = 0;
        for (int element : numbers)
        {
            if (number == element)
                count++;
        }
        return count;
    }
}

然后打电话...

public class Caller {

    public static void main(String[] args)
    {
        int[] b = { 1, 2, 3};
        int c = Digits.numberCount(b, 2);
        System.out.println(c);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM