簡體   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