簡體   English   中英

對於參數類型 int[], int 未定義運算符 %

[英]The operator % is undefined for the argument type(s) int[], int

我有一個代碼,但它顯示錯誤運算符 % 未定義參數類型 int[], int

public class Test {
public static void main(String [] args) {  
    int[] n = {2,3,5,7};
    System.out.println(arePrimeFactors(n));      
    }
    public static boolean arePrimeFactors(int[] n){
            boolean a = arePrimeFactors(n); 
                        if (n%2==0) {
                            return false;
               for(int i=3;i*i<=n;i+=2) {
                        if(n%i==0)
                            return false;
        }
               return true;
            }}}

你們能檢查一下我是 Java 新手嗎謝謝

因為n是一個數組,所以您需要指定在哪個元素上使用模數運算符:

if (n[index] % 2 == 0) {
    //So stuff...
}

一個數組可以在多個索引處包含多個值,例如: n范圍可以從{1, 6, 4, 2, 8}{10245, 23451, 35312, 1} 您需要將索引號傳遞到括號中以指定您正在使用的元素

考慮一下:如果你有一個數組int[] i = {1, 2, 3, 4}; 並且您想引用2 ,而不是鍵入i[1] 這是因為在 Java 中索引從 0 開始,而不是從 1 開始,因此對於第二個元素,您將傳遞1而不是2 這張圖讓你明白我的意思:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM