-3

我是 Java 新手,正在开发一个基本程序,该程序查看数组并打印数组中可被 3 整除的数字数量。我在让它正常工作时遇到了一些麻烦。这是我到目前为止的代码。

package arraysearch;

public class Intsearch {

    public static void main(String[] args) {

    }

    public static void multiple_3 (int[] a, int b)  {
        b=0;        
    }
    {
        int[] numarray ={3, 9, 45, 88, 23, 27, 68};
        {
            if (numarray % 3)==0;
                b = b+1;
        }
        System.out.println("This is the amount of numbers divisible by 3:" +b)
    }   
}
4

3 回答 3

5

试试这个(Java 7):

public static void main(String[] args) {
    multiple_3(new int[] { 3, 9, 45, 88, 23, 27, 68 });
}

public static void multiple_3(int[] ints) {
    int count = 0;
    for (int n : ints) {
        if (n % 3 == 0) {
            count++;
        }
    }
    System.out.println("This is the amount of numbers divisible by 3: " + count);
}

Java 8 更新:

public static void multiple_3(int[] ints) {
    long count = IntStream.of(ints).filter(n -> n % 3 == 0).count();
    System.out.println("This is the amount of numbers divisible by 3: " + count);
}
于 2011-06-06T02:52:39.670 回答
0

您需要一个 for 循环来按顺序评估数组中的每个项目:

 int[] numarray = { 1, 2, 3 };
 for (int i = 0; i < numarray.Length; i++)
 {
     if (numarray[i] % 3 == 0)
     {
         b++;
     }
 }
于 2011-06-06T02:54:28.903 回答
0

请试试 :

   int b=0;        

   int[] numarray ={3, 9, 45, 88, 23, 27, 68};

   for ( int i=0; i<numarray.length; i++)
   {   
       if (numarray[i]%3==0)
           b++;
   }   
   System.out.println("This is the amount of numbers divisible by 3:" +b)
于 2011-06-06T02:55:16.923 回答