Skip to content
Advertisement

how to check the range using only if statement

How can I write the code with a specific requirement having the range between frontR and frontL that must be between 1-3?

Code:

System.out.println("Input right front pressure: ");
frontR = keyboard.nextInt();

if (frontR >= 32 && frontR <= 42) {
    inflation = "good";
}
else{
        warning = "Warning: pressure is out of range";
        inflation = "BAD";
}

System.out.println("Input left front pressure: ");
frontL = keyboard.nextInt();

if (frontL >= 32 && frontL <= 42) {
    inflation = "good";
}
else {
    warning = "Warning: pressure is out of range";
    inflation = "BAD";
}

Advertisement

Answer

if you want to check the difference between two numbers, you need to subtract them. The result may be negative if the first number is smaller than the second, so you may want to use Math.abs() which will make it positive again. Then you have a positive number that you can check for being between 1 and 3:

int difference = Math.abs(frontL - frontR);

if (difference >= 1 && difference <= 3) {
    inflation = "good";
}
else {
    warning = "Warning: difference between pressure left and right detected";
    inflation = "BAD";
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement