0

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;
    }
3
  • Use an Interface, which offers a contract to make that check in your objects. Commented Feb 3, 2022 at 3:54
  • 1
    Presumably your object has some field or method that gives you the number... Commented Feb 3, 2022 at 3:57
  • You can create a span and use span.contains(...) sourceforge.net/p/tus/code/HEAD/tree/tjacobs/util/Span.java Commented Feb 3, 2022 at 4:04

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

how would you compare the data directly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.