Вывести количество чисел в массиве, кратное 3 - PullRequest
0 голосов
/ 06 июня 2011

Я новичок в 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)
    }   
}

Ответы [ 3 ]

5 голосов
/ 06 июня 2011

Попробуйте это (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);
}
0 голосов
/ 06 июня 2011

Пожалуйста, попробуйте:

   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)
0 голосов
/ 06 июня 2011

Вам понадобится цикл for для последовательной оценки каждого элемента в массиве:

 int[] numarray = { 1, 2, 3 };
 for (int i = 0; i < numarray.Length; i++)
 {
     if (numarray[i] % 3 == 0)
     {
         b++;
     }
 }
...