Kaspar Froyen Kaspar Froyen - 3 months ago 23
Java Question

Either counting or filtering an array of random integers based on specific characteristics

I'm taking an introduction to programming class this semester and so far it's been fun but it's really kicked my butt. My problem is that I must create an array of random integers from 0-100 and count the number of single digit integers that are produced.

So far I have this:

public class randomarray {
public static void main(String[] args) {

int i;
int smallintegers;
int[] RandomArray = new int[10];
for(i = 0; i < RandomArray.length; i++) {
RandomArray[i] = (int)(Math.random() * 100);
System.out.print(RandomArray[i] + " ");

This works and creates an array of random digits like so:

17 56 44 41 42 96 8 42 21 86

Now I need to find out a way to count the number of single digit integers, and in this case it would have been 1. The first method I thought of would be to use filter() to copy the single-digit integers, create a new array from filter(), and then produce the length of the new array. But I'm damn near certain there has to be a simpler way to do this, and that I might be thinking a bit too much.

Thanks a lot for the help.


How about checking for single digit integers while you are building the array:

int numSingle = 0;
for (i=0; i < RandomArray.length; i++) {
    int num = (int)(Math.random() * 100);
    if (num < 10) ++numSingle;
    RandomArray[i] = num;
    System.out.print(num + "  ");

System.out.println("There are " + numSingle + " integers in the array.");

If, for some reason, you can't check the array as it's being built (e.g. you are receiving it from some API you can't control), then you can go with the Wombat's suggestion to just iterate the array. If you use a Java 8 stream to do this I expect it would also iterate over the array internally.

Here is how you could use a stream to answer the same question:

int numSingle = Arrays.stream(RandomArray).filter(n -> n < 10).toArray().length;