user17607040
user17607040

Reputation:

how do I check if each value of an array is between a range if the array is a non primitive type

Basically, I want to check each value of dice.

If the value is ranges between 1 and 6, inclusive, then I want to such value into the array count.

The problem is that dice is an object, not a primitive, which I declared earlier thus the >= operator does not work.

    public int[] getValueCount() {
        int[] count;
        for (int i = 0; i < dice.length; ++i) {
        if ((dice[i] >= 0) && (dice[i] <= 6)) {
                count[i] = dice[i];
            }
        }
        return count;
    }

Upvotes: 0

Views: 44

Answers (2)

acarlstein
acarlstein

Reputation: 1838

I regret to inform you that Java doesn't support operator overloading like other languages such as C++. It was a decision made by the designers with the hope that would make the language simpler to use.

However, there are other options available that you could implement.

The one option that could work very well for you, could be implementing the the Comparable interface.

import java.lang.Comparable;

public class Dice implements Comparable<Dice> {

    /* Code */

    @Override
    public int compareTo(Dice otherDice) {
        return this.value - otherDice.value;
    }
}

https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html

The good thing is that you can apply many things with it such as using the Comparator interface:

Comparator<Dice> compareByValue = Comparator.comparing(Dice::getValue);

I hope this helps you out.

Upvotes: 1

&#193;ngel Talero
&#193;ngel Talero

Reputation: 127

Implement your own comparison method inside Dice class '.greaterOrEqual(x)' or access the data on Dice class directly and compare that value instead

Upvotes: 0

Related Questions