Andrew .Del Real
Andrew .Del Real

Reputation: 39

Counting number divisible by 10 in an array

I was given an assignment that made me create 3 methods that created an array, print an array, and count all the numbers divisible by 10 in a array. The part that is giving me the most trouble is counting the numbers divisible by 10. the is the code I have so far:

public int[] createArray(int size) {

    Random rnd = new Random();
    int[] array = new int[size];

    for (int i = 0; i < array.length; i++) {
        array[i] = rnd.nextInt(101);
    }
    return array; 
}

public void printArray() {

    Journal5a call = new Journal5a();
    int[] myArray = call.createArray(10);

    for (int i = 0; i < myArray.length; i++) {
        System.out.println(myArray[i]);
    }
    System.out.println("There are " + call.divideByTen(myArray[i]) + " numbers that are divisable by 10");
}

public int divideByTen(int num) {

    int count = 0;

    if (num % 10 == 0) {
        count++;
    }
    return count;        
}

public static void main(String[] args) {

    Journal5a call = new Journal5a();
    Random rnd = new Random();

    call.printArray();
}

Upvotes: 2

Views: 2256

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201447

Pass an array to the method, and use that for determining the count. Your algorithm looks reasonable. Something like,

public int divideByTen(int[] nums) {
    int count = 0;
    for (int num : nums) {
        if (num % 10 == 0) {
            count++;
        }
    }
    return count;
}

or, in Java 8+, use an IntStream and filter like

return (int) IntStream.of(nums).filter(x -> x % 10 == 0).count();

Then you can call it like

System.out.println("There are " + call.divideByTen(myArray) 
        + " numbers that are divisible by 10");

or with printf and inline like

System.out.printf("There are %d numbers that are divisible by 10.%n", 
        IntStream.of(nums).filter(x -> x % 10 == 0).count());

Upvotes: 5

Hemal
Hemal

Reputation: 3760

You can do it this way. Pass full array and then check for division by 10. Skipped other part for simplicity.

public void printArray() {

    Journal5a call = new Journal5a();
    int[] myArray = call.createArray(10);

    divideByTen(myArray);
}

public int divideByTen(int[] num) {

    int count = 0;
    for(i=0;i<num.length;i++)
    {
        if (num[i] % 10 == 0) {
            count++;
        }
    }
    return count;        
}

Upvotes: 0

Related Questions