简体   繁体   中英

Variable inside for loop doesnt connect with the outside

How can i make the overHalfSum integer add up with every for loop ? Note that the compiler warns me that overHalfSum is not used.

    int overHalfSum=0;

    for (int i=0;i<20;i++){
        if (sensorPol[i].getCo()>0.5){
            overHalfSum += 1;
        }
    }
    for (int i=0;i<20;i++){
        if (sensorTemp[i].getMax()>0.5){
            overHalfSum += 1;
        }
    }   
    for (int i=0;i<10;i++){
        if (camera[i].getLoad()>0.5){
            overHalfSum += 1;
        }

You increment the variable, but never read its value. The code is equivalent to:

int overHalfSum=0;

for (int i=0;i<20;i++){
    sensorPol[i].getCo();
}
for (int i=0;i<20;i++){
    sensorTemp[i].getMax();
}   
for (int i=0;i<10;i++){
    camera[i].getLoad();
}

(and the calls in the for loops like sensorPol[i].getCo(); may be removable as well, if they have no side effect).

You need to actually read the variable's value for it to be "used", eg add this after the logic in your question:

System.out.println(overHalfSum);

The compiler says that you didn't use the variable because in the snipped you provided you only give the variable a value and change the value. You never use it in a function or with other variables.

Better check whether the conditions are met.

Maybe try to add a System.out.writeln('added 1 to overHalfSum') to see if it works like you want it to work.

if (sensorPol[i].getCo()>0.5){
    overHalfSum += 1;
    System.out.writeln('added 1 to overHalfSum');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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