logic101
logic101

Reputation: 211

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

}

Upvotes: 0

Views: 322

Answers (1)

Bohemian
Bohemian

Reputation: 425043

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

Upvotes: 1

Related Questions