bob
bob

Reputation: 21

Is there a way to have less if-statements?

This program is supposed to print out the number of times each number has been generated of 100 random numbers in the scale of 1 to 10 (then put it in the array).

I can't think of any other way than to have an if-statement for each number. Is there any way to avoid so many if statements by another code or something?

public static void countNumbers() {
    Random generator = new Random();

    int arr[] = new int[101];
    int add[] = new int[10];

    for (int i = 0; i < 100; i++) {
        int sum = 0;
        arr[i] = generator.nextInt(10)+1;

        if(arr[i] ==1){
            add[0]++;
        }
        if(arr[i] ==2){
            add[1]++;
        }
        if(arr[i] ==3){
            add[2]++;
        }
        if(arr[i] ==4){
            add[3]++;
        }
        if(arr[i] ==5){
            add[4]++;
        }
        if(arr[i] ==6){
            add[5]++;
        }
        if(arr[i] ==7){
            add[6]++;
        }
        if(arr[i] ==8){
            add[7]++;
        }
        if(arr[i] ==9){
            add[8]++;
        }
        if(arr[i] ==10){
            add[9]++;
        }
    }

    System.out.println(Arrays.toString(add));
    System.out.println();
}

Upvotes: 2

Views: 97

Answers (4)

Albert Bos
Albert Bos

Reputation: 2052

I think it is good to re-use the size of you add[] this way you can keep your code more flexible.

int add[] = new int[10];

for (int i = 0; i < 100; i++) {
    int index = generator.nextInt(add.length);
    arr[index]++;
}

Upvotes: 2

Eran
Eran

Reputation: 393771

You should note that all your if statements have a similar structure :

if(arr[i] ==x){
    add[x-1]++;
}

Therefore they can be replaced by add[arr[i]-1]++;.

You only need a single if statement to validate that you don't get out of the bounds of the add array :

if (arr[i] <= 10 && arr[i] >= 1) {
     add[arr[i]-1]++;
}

EDIT :

As assylias commented, you don't really need the if statement, since you initialize your arr array to values between 1 and 10.

Upvotes: 7

assylias
assylias

Reputation: 328568

Your whole method can be replaced by:

public static void countNumbers() {
    Random generator = new Random();

    int add[] = new int[10];

    for (int i = 0; i < 100; i++) {
        add[generator.nextInt(10)]++;
    }

    System.out.println(Arrays.toString(add));
    System.out.println();
}

The other variables (such as the arr array) are not used at the moment so I suggest getting rid of them until you actually need them.

Upvotes: 2

m0nhawk
m0nhawk

Reputation: 24148

Yes.

If you notice, you have a repeating pattern:

if(arr[i] == 1){
    add[0]++;
}

Then you can replace it with the next one:

add[arr[i] - 1]++;

And the resulting for will look alike:

for (int i = 0; i < 100; i++) {
    arr[i] = generator.nextInt(10) + 1;
    add[arr[i] - 1]++;
}

Upvotes: 3

Related Questions