开发者

Print amount of numbers in array divisible by 3

开发者 https://www.devze.com 2023-03-11 02:43 出处:网络
I\'m new to Java and working on a basic program开发者_Go百科 that looks through an array and gives prints the amount of numbers in the array that are divisible by 3. I\'m having some trouble getting i

I'm new to Java and working on a basic program开发者_Go百科 that looks through an array and gives prints the amount of numbers in the array that are divisible by 3. I'm having some trouble getting it to work right. Here is the code that I've got so far.

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


Try this (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 update:

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


You'll need a for loop to evaluate each item in the array sequentially:

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


Please try :

   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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号