I am trying to make the code more efficient, but don’t know how to apply it in my code. What I have in mind is changing the integers insideIsGreater
and outsideIsGreater
into boolean values. The only problem after that is that I do not know where to begin changing my code. Does anyone care to help?
int amountPassed = 0; int insideIsGreater = 0; int outsideIsGreater = 0; for (Measurement measurement : measurements) { double outsideTemp = measurement.getOutsideTemp(); // gets the outside temperature double insideTemp = measurement.getInsideTemp(); // gets the inside temperature if (outsideTemp > insideTemp) { if (outsideIsGreater == 0) { amountPassed++; outsideIsGreater += 1; insideIsGreater = 0; } } else { if (insideTemp > outsideTemp) { if (insideIsGreater == 0) { amountPassed++; insideIsGreater += 1; outsideIsGreater = 0; } } } }
Advertisement
Answer
int amountPassed = 0; boolean isInsideIsGreater = false; boolean isOutsideIsGreater = false; for (Measurement measurement : measurements) { double outsideTemp = measurement.getOutsideTemp(); // gets the outside temperature double insideTemp = measurement.getInsideTemp(); // gets the inside temperature if (outsideTemp > insideTemp) { if (!isOutsideIsGreater) { amountPassed++; } isOutsideIsGreater = true; isInsideIsGreater = false; } else if (insideTemp > outsideTemp) { if (!isInsideIsGreater) { amountPassed++; } isInsideIsGreater = true; isOutsideIsGreater = false; } else { // temperature is same isInsideIsGreater = false; isOutsideIsGreater = false; } }