Search code examples
javaarraysint

Incompatible operand types int and int[]


I am working on a Java application that recognizes the weight of a phone and writes the values to a database. However I have ran into the issue where the weight int isn't compatible to the values in the array 'phoneWeight' in the if statement. I was wondering if there is a simple way to overcome this?

    int weight = (data[4] & 0xFF) + (data[5] << 8);
    boolean phoneOnScale = false;
    int[] phoneWeight = {140, 150};

    System.out.println("My Weight: " + weight);

    if (weight == phoneWeight) {
        phoneOnScale = true;
        System.out.println("Phone is on scale");

Solution

  • weight == phoneWeight is attempting to compare an int (weight), and an int[] (phoneWeight). This could never be true.

    If you want to check if it's between the two numbers in the array, you'd have to explicitly check for that:

    if(phoneWeight[0] <= weight && weight <= phoneWeight[1]) {
    

    Use < instead of <= if you want the bounds to be exclusive. This also assumes that the first number is the lower bound, while the second number is the upper bound.