简体   繁体   English

不兼容的操作数类型 int 和 int[]

[英]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.我正在开发一个 Java 应用程序,它可以识别手机的重量并将值写入数据库。 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.但是,我遇到了一个问题,即重量 int 与 if 语句中数组“phoneWeight”中的值不兼容。 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");

This is an array of int's.这是一个int数组。 You cannot compare an int to an array.您不能将 int 与数组进行比较。

int[] phoneWeight = {140, 150};

You must check if weight is higher than mininum value and lower than maximum value, for phone to be on scale (between the two values), if I understood you right.如果我理解正确,您必须检查重量是否高于最小值并低于最大值,以便电话按比例(在两个值之间)。

weight == phoneWeight is attempting to compare an int ( weight ), and an int[] ( phoneWeight ). weight == phoneWeight试图比较int ( weight ) 和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.这也假设第一个数字是下限,而第二个数字是上限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM