简体   繁体   中英

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

Hi i wrote a method to calculate the number of times a number appears in an array.The problem is it works when written in the same class as the main program but does not work when its written in a different 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;
          }

}

it works in the above instance but when not when i try to use the method from another class but in the same project

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;
    }

}

You seem confused... Here's how you would use it, plus see the use of the foreach loop to make you code cleaner:

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;
    }
}

And then to call...

public class Caller {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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